[LeetCode By Go 96]434. Number of Segments in a String

题目

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

解题思路

  1. 遍历字符串,先跳过所有空格,然后如果没到结尾,并且找到一个不是空格的字符,count加1,然后跳过所有非空格字符
  2. 循环以上过程知道字符串结束

代码

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
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/4a57465ab0c5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞