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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容