10/21 檢查詞組排序
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.
Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 20order.length == 26- All characters in
words[i]andorderare English lowercase letters.
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
My_dict={}
for ind,ele in enumerate(order):
My_dict[ele] = ind
for word_1,word_2 in zip(words,words[1:]):
if word_1==word_2:
continue
c=0
for i,j in zip(word_1,word_2):
if i == j :
c+=1
continue
elif My_dict[i]< My_dict[j]:
'直接檢查下一組'
break
if My_dict[i] > My_dict[j]:
return False
if len(word_1) > len(word_2) and c==len(word_2):
'前面相等, 到 word_1還餘, 所以出現word_1索引對上空元素'
return False
return True
--------------------------
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
positions = {c:i for i,c in enumerate(order)}
for w1, w2 in zip(words, words[1:]):
for c1, c2 in zip(w1, w2):
if c1 != c2:
if positions[c1] > positions[c2]:
return False
break
else:
if len(w1) > len(w2):
return False
return True--------------------------
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
mapping = {c: chr(ord('a')+i) for i, c in enumerate(order)}
def tfm(word):
return "".join([mapping[c] for c in word])
for i in range(len(words)-1):
if tfm(words[i]) > tfm(words[i+1]):
return False
return True
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁