字符串中的单词数
题目描述:
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: “Hello, my name is John”
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 “Hello,” 算作 1 个单词。
提示:
- 2 <= nums.length <= 104
- -109 <= nums[i] <= 109
- -109 <= target <= 109
- 只会存在一个有效答案
解法
模拟过程即可。
代码
class Solution:
def countSegments(self, s: str) -> int:
res, idx = 0, 0
while idx < len(s):
if s[idx] == " ":
idx += 1
else:
res += 1
while idx < len(s) and s[idx] != " ":
idx += 1
return res
测试结果
执行用时:28 ms, 在所有 Python3 提交中击败了 84.63% 的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了 38.93% 的用户
说明
算法题来源:力扣(LeetCode)