LeetCode每日一題: 字符串中的單詞數(No.434)

題目: 字符串中的單詞數


統計字符串中的單詞個數,這裏的單詞指的是連續的不是空格的字符。
請注意,你能夠假定字符串裏不包括任何不可打印的字符。
複製代碼

示例:


輸入: "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;
    }
}複製代碼
相關文章
相關標籤/搜索