LeetCode

LeetCode434. Number of Segments

2017-02-23  本文已影响8人  Persistence2

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.

思路:

代码(自己写的 好开心)

public class Solution {
    public int countSegments(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        int len = s.length();
        int res = 0;
        int index = 1;
        if (s.charAt(0) != ' ') {
            res++;
        }
        while(index < len-1) {
            if(s.charAt(index) == ' ' && s.charAt(index+1) != ' ') {
                res++;
            }
            index++;
        }
        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读