【发布时间】:2019-10-07 03:15:16
【问题描述】:
问。给定以外来语言书写的单词序列和字母顺序,当且仅当给定单词在该外来语言中按字典顺序排序时,才返回 true。 以下是一些例子:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
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.
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.
以下是我的解决方案:
class Solution(object):
def isAlienSorted(self, words, order):
orderDict = {}
for index, char in enumerate(order):
orderDict[char] = index
for j in range(len(words)-1):
for i in range(min(len(words[j]),len(words[j+1]))):
word1 = words[j]
word2 = words[j+1]
if orderDict[word1[i]] == orderDict[word2[i]]:
continue
if orderDict[word1[i]] > orderDict[word2[i]]:
return False
if orderDict[word1[i]] < orderDict[word2[i]]:
return True
if len(words[j]) > len(words[j+1]):
return False
return True
为什么只有 73/115 个测试用例通过了?
【问题讨论】:
-
是 Python 3 还是 Python 2?你已经标记了两者。
-
不管怎样,
return True不好。您只确定了words[j]和words[j + 1]在这一点上的顺序正确,而不是其余的。相反,使用break退出循环,并弄清楚如何跳过长度检查。 (Python 甚至有一种独特的方式来做到这一点。) -
你为什么要使用类来做到这一点?
-
@Ry- 在 python 中退出循环的独特方式是什么?
-
不是退出循环,而是在使用
break退出时跳过长度检查。for…else
标签: python data-structures testcase