LeetCode434. 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.

思路:

  • 找到转换点(前一个是空格,后一个是字母)
  • 处理边界问题

代码(自己写的 好开心)

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;
    }
}

你可能感兴趣的:(LeetCode434. Number of Segments in a String)