美文网首页LeetCode
LeetCode434. Number of Segments

LeetCode434. Number of Segments

作者: Persistence2 | 来源:发表于2017-02-23 23:33 被阅读8次

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

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