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

迷南。 2022-06-12 00:28 243阅读 0赞

题目大意

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

解题思路

split()

代码

  1. return len(s.split())

总结

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

  1. class Solution(object):
  2. def countSegments(self, s):
  3. """
  4. :type s: str
  5. :rtype: int
  6. """
  7. ss = list(s)
  8. count = 1
  9. flag = 0
  10. for i in range(len(ss)):
  11. if ord(ss[i])>=48 and ord(ss[i])<=57:
  12. flag = 0
  13. continue
  14. elif ord(ss[i])>=65 and ord(ss[i])<=90:
  15. flag = 0
  16. continue
  17. elif ord(ss[i])>=97 and ord(ss[i])<=122:
  18. flag = 0
  19. continue
  20. else:
  21. if flag == 1:
  22. flag = 0
  23. continue
  24. # print(ss[i], ord(ss[i]))
  25. count +=1
  26. flag = 1
  27. return count

提交后是错的,因为:

  1. Input:
  2. "love live! mu'sic forever"
  3. Output:
  4. 5
  5. Expected:
  6. 4

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

发表评论

表情:
评论列表 (有 0 条评论,243人围观)

还没有评论,来说两句吧...

相关阅读