LeetCode每日一题: 字符串中的单词数(No.434)

1,530 阅读1分钟

题目: 字符串中的单词数


统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。

示例:


输入: "Hello, my name is John"
输出: 5per", t = "title"

思考:


这道题可以认为当前字符的前一个字符是空格,当前字符不为空格,则认为这是一个新的单词。
按照这个思想,循环判断字符串中的字符,计算单词数量。

实现:


    class Solution {
    public int countSegments(String s) {
        int count = 0;
        //是否为空格
        boolean isBlank = true;
        for (int i = 0; i < s.length(); i++) {
            //当前字符为空格
            if (s.charAt(i) == ' ') {
                isBlank = true;
            } else {//当前字符不为空格
                if (isBlank) {//前一个字符为空格
                    count++;//单词数+1
                }
                isBlank = false;
            }
        }
        return count;
    }
}