classSolution: defnumsSameConsecDiff(self, N, K): """ :type N: int :type K: int :rtype: List[int] """ if N == 1: return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ret = [] hashmap = {} for i inrange (10): hashmap[i] = [] if K == 0: hashmap[i].append(i) else: if i + K <= 9: hashmap[i].append(i + K) if i - K >= 0: hashmap[i].append(i - K) defhelper(n, digits): if n == N: ret.append(reduce(lambda x, y: x * 10 + y, digits)) return for i in hashmap[digits[n-1]]: digits.append(i) helper(n+1, digits) digits.pop() for i inrange(1, 10): digits = [i] helper(1, digits) return ret
966. Vowel Spellchecker
由于前2题用brute search都解决了,本题我也上来就直接干。结果TLE了,因为暴力法的时间复杂度为O(MN),M = len(wordlist), N = len(queries)。
怎样才能进一步降低时间复杂度呢?我脑子中闪过的第一个词是 单词书(Tire),最近刚在 算法第四版 中学到这一技术。 时间复杂度为O(max(N * wordlist中最长单词的长度, M), 不出意料的话,可以AC,现在已经11:46了。应该写不完了,让我先看一下第4题吧。
classSolution: defspellchecker(self, wordlist, queries): """ :type wordlist: List[str] :type queries: List[str] :rtype: List[str] """ wordlist_replace_vowel = [] vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] word_lower = [] for word in wordlist: word_lower.append(word.lower()) temp = list(word) for i inrange(len(temp)): if temp[i] in vowel: temp[i] = '0' wordlist_replace_vowel.append(''.join(temp).lower()) ret = [] for query in queries: flag = 0 match = '' temp = list(query) for i inrange(len(temp)): if temp[i] in vowel: temp[i] = '0' query_replace_vowel = ''.join(temp).lower() query_lower = query.lower() for wi, word inenumerate(wordlist): if flag < 4and word == query: match = word flag = 4 break if flag < 3and word_lower[wi] == query_lower: match = word flag = 3 if flag < 2and wordlist_replace_vowel[wi] == query_replace_vowel: match = word flag = 2 ret.append(match) return ret
classSolution: defspellchecker(self, wordlist, queries): """ :type wordlist: List[str] :type queries: List[str] :rtype: List[str] """ wordlist_replace_vowel = {} vowel = ['a', 'e', 'i', 'o', 'u'] word_lower = {} word_set = set(wordlist) for word in wordlist: wl = word.lower() # setdefault 的使用:第一次赋值,之后忽略。保证在wordlist中先出现的词优先 word_lower.setdefault(word.lower(), word) wordlist_replace_vowel.setdefault(''.join('0'if i in vowel else i for i in wl), word) ret = [] for query in queries: ql = query.lower() query_replace_vowel = ''.join('0'if i in vowel else i for i in ql) if query in word_set: ret.append(query) elif ql in word_lower: ret.append(word_lower[ql]) elif query_replace_vowel in wordlist_replace_vowel: ret.append(wordlist_replace_vowel[query_replace_vowel]) else: ret.append('') return ret