您的位置:首页 > 编程语言 > Python开发

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

2017-07-11 01:04 525 查看

题目大意

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

解题思路

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:
5
Expected:
4


之后才意识到自己想复杂了,有空格就可以了。。。

不过代码中flag的作用是记录上一轮循环发生的结果,在其他代码编写中中可以作为一个用例。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode string