美文网首页LeetCode By Go
[LeetCode By Go 96]434. Number o

[LeetCode By Go 96]434. Number o

作者: miltonsun | 来源:发表于2017-09-06 16:24 被阅读18次

    题目

    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
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 96]434. Number o

        本文链接:https://www.haomeiwen.com/subject/solvjxtx.html