【Leetcode】【python】Number of Segments in a String

来源:互联网 发布:免费查询大数据征信 编辑:程序博客网 时间:2024/05/22 05:16

题目大意

计算字符串中的非空子串的个数。

解题思路

split()

代码

return len(s.split())

总结

这题对于python来说有点智障,然而智障的我还是把他想复杂了,我写的是:

class Solution(object):    def countSegments(self, s):        """        :type s: str        :rtype: int        """        ss = list(s)        count = 1        flag = 0        for i in range(len(ss)):            if ord(ss[i])>=48 and ord(ss[i])<=57:                flag = 0                continue            elif ord(ss[i])>=65 and ord(ss[i])<=90:                flag = 0                continue            elif ord(ss[i])>=97 and ord(ss[i])<=122:                flag = 0                continue            else:                 if flag == 1:                    flag = 0                    continue                # print(ss[i], ord(ss[i]))                count +=1                flag = 1        return count

提交后是错的,因为:

Input:"love live! mu'sic forever"Output:5Expected:4

之后才意识到自己想复杂了,有空格就可以了。。。
不过代码中flag的作用是记录上一轮循环发生的结果,在其他代码编写中中可以作为一个用例。