Posted on 2023-02-02 21:07
Uriel 閱讀(55)
評論(0) 編輯 收藏 引用 所屬分類:
字符串處理 、
閑來無事重切Leet Code
給出26個字母的另一種順序以及這個順序下的幾個單詞,問是否符合字母序。
用dict構建原本的26個字母和新字母序列的映射,將新序的單詞映射回原始26個字母序,再直接對比相鄰字符串
1 #953
2 #Runtime: 18 ms (Beats 91.10%)
3 #Memory: 13.4 MB (Beats 76.87%)
4
5 class Solution(object):
6 def isAlienSorted(self, words, order):
7 """
8 :type words: List[str]
9 :type order: str
10 :rtype: bool
11 """
12 ori_id = dict()
13 a = "abcdefghijklmnopqrstuvwxyz"
14 for i in range(26):
15 ori_id[order[i]] = a[i]
16 for i in range(len(words)):
17 trans_s = []
18 for j in words[i]:
19 trans_s.append(ori_id[j])
20 trans_s = ''.join(trans_s)
21 if i == 0:
22 pre = trans_s
23 else:
24 if pre > trans_s:
25 return False
26 pre = trans_s
27 return True