classSolution: defcountValidWords(self, sentence: str) -> int: defisPunctuation(c): return c == '!'or c == '.'or c == ',' defisLower(c): returnord(c) >= ord('a') andord(c) <= ord('z') defcheck(word): # It only contains lowercase letters, hyphens, and/or punctuation (no digits). # There is at most one hyphen '-'. If present, it should be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid). # There is at most one punctuation mark. If present, it should be at the end of the token. hyphenCount = 0 punctuationCount = 0 for c in word: if c == '-': hyphenCount += 1 if c.isdigit(): returnFalse if isPunctuation(c): punctuationCount += 1 if hyphenCount > 1or punctuationCount > 1: returnFalse if punctuationCount == 1andnot isPunctuation(word[-1]): returnFalse if hyphenCount == 1: l = word.split('-') iflen(l) != 2: returnFalse ifnot (len(l[0]) >= 1and isLower(l[0][-1])) ornot (len(l[1]) >= 1and isLower(l[1][0])): returnFalse returnTrue ans = 0 words = sentence.split() for word in words: # print (word) if check(word): # print('Yes') ans += 1 return ans
时间复杂度:O(N)。
空间复杂度:O(N)。
使用 re,也就是正则表达式,可以得到更简单的解法。
1 2 3 4 5 6 7 8 9 10 11
import re
classSolution: defcountValidWords(self, sentence: str) -> int: pattern = re.compile('(^[a-z]+(-[a-z]+)?)?[,.!]?$') word_count = 0 for word in sentence.split(): if pattern.match(word): word_count = word_count + 1
return word_count
时间复杂度:O(N)。
空间复杂度:O(N)。
2048. 下一个更大的数值平衡数
很多人通过暴力枚举得到了 Accepted:遍历每个大于 n 的数,检查它是否为数值平衡数。
我在比赛中提出了更好的解法。因为 0 <= n <= 10^6,可以手动枚举所有数值平衡数,再找到下一个更大的数。可能的平衡数数量是有限的。这里的一个技巧是使用 permutations 遍历字符串的所有排列。
classSolution: defnextBeautifulNumber(self, n: int) -> int: # 1digit: 1 # 2digit: 22 # 3digit: 333 or 1+2 # 4digit: 1+3 or 4 # 5digit: 5 or 1+4 or 2+3 # 6digit: 6 or 1+5 or 2+4 or 1+2+3 # 7digit: 7 or 1+6 or 1+2+4 1224444 if n == 10**6: return1224444 ans = 1224444 s = str(n) # 6! 720 defcheck(l): ans = float('inf') origin = '' for i in l: origin += str(i) * i perms = [''.join(p) for p in permutations(origin)] for s in perms: i = int(s) if i > n: ans = min(ans, i) return ans
ans = min(ans, check([6])) ans = min(ans, check([1, 5])) ans = min(ans, check([2, 4])) ans = min(ans, check([1, 2, 3])) ans = min(ans, check([5])) ans = min(ans, check([1, 4])) ans = min(ans, check([2, 3])) ans = min(ans, check([4])) ans = min(ans, check([1, 3])) ans = min(ans, check([3])) ans = min(ans, check([1, 2])) ans = min(ans, check([2])) ans = min(ans, check([1])) return ans