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
非常简单,题目已经说了,所谓segment就是连续的一段非空字符串,那么就是增加一个标记就行了,记录是否开始扫描一个字符串了,只要连续不断,都认为是一个,一旦中断了,那么标记重新开始计算。
go里面,判断rune需要用 ' '
, 切记不可以用" "
func countSegments(s string) int {
ret := 0
segmentBegin := false
for _, n := range s {
if segmentBegin {
if n == ' ' {
segmentBegin = false
}
} else {
if n != ' ' {
segmentBegin = true
ret++
}
}
}
return ret
}