本文主要是介绍Leetcode 2047. Number of Valid Words in a Sentence [Python],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
展开了,把不符合条件的全部返回False。细心点就好了。
class Solution:def countValidWords(self, sentence: str) -> int:lst = sentence.split(' ')hyphens = Falseres = 0#print(lst)for part in lst:if part == '':continueif self.check(part):res += 1#print(part)#print(' ')return resdef check(self, part):N = len(part)countpunc = 0counthyphen = 0for i, letter in enumerate(part):if letter.isdigit():return Falseif letter.isalpha():continueif N > 1 and i < N- 1 and (letter == '!' or letter == ',' or letter == '.'):return False#寻找合法的puncif letter == '!' or letter == ',' or letter == '.':countpunc += 1if countpunc > 1:return False#punc重复if letter == '-' and (i == 0 or i == N-1):return False#hyphen不在头尾if letter == '-' and (not part[i-1].isalpha() or not part[i+1].isalpha()):return False#hyphen前后不都是letterif letter == '-':counthyphen += 1if counthyphen > 1:return False#hyphen重复return True
这篇关于Leetcode 2047. Number of Valid Words in a Sentence [Python]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!