题目
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
解题思路
- 遍历字符串,先跳过所有空格,然后如果没到结尾,并且找到一个不是空格的字符,count加1,然后跳过所有非空格字符
- 循环以上过程知道字符串结束
代码
func countSegments(s string) int {
len1 := len(s)
if 0 == len1 {
return 0
}
var count int
for i := 0; i < len1; {
for ;i < len1 && ' ' == s[i];i++ {}
if i >= len1 {
break
}
count++
for ;i < len1 && ' ' != s[i]; i++ {}
}
return count
}
网友评论