Number of Segments in a String Leetcode

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

 

这道题用了split什么的都过不了,后来还是用指针解决了,所以还是手撕代码比较有效?但是最近老是喜欢用双指针,代码不够优雅。。。

public class Solution {
    public int countSegments(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int pre = 0, cur = 0, sum = 0;
        for (int i = 0; i < s.length(); i++) {
            if (pre == 0 && cur == 0 && s.charAt(cur) != ' ') {
                sum++;
            }
            if (s.charAt(pre) == ' ' && s.charAt(cur) != ' ') {
                sum++;
            }
            pre = cur;
            cur++;
        }
        return sum;
        
    }
}

不用指针,优雅多了。。。

public class Solution {
    public int countSegments(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                sum++;
            }
        }
        return sum;
        
    }
}

 

posted @ 2017-01-19 06:04  璨璨要好好学习  阅读(156)  评论(0编辑  收藏  举报