LeetCode434. 字串中的單詞數
阿新 • • 發佈:2019-01-22
統計字串中的單詞個數,這裡的單詞指的是連續的不是空格的字元。
請注意,你可以假定字串裡不包括任何不可列印的字元。
示例:
輸入: "Hello, my name is John" 輸出: 5思路:從第二個單詞起,每出現一個單詞的條件必是空字元後出現非空字元,例如:‘ ’+'m' 出現my; ' '+'n' 出現name 等等。因此,只需統計空字元後緊跟著出現非空字元的次數即可。別忘了如果字串剛開始就出現空字元,則不用加上第一個單詞。
class Solution { public int countSegments(String s) { if(s.length()==0||s==null) { return 0; } int count=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)==' ') { if(i<s.length()-1) { if(s.charAt(i+1)!=' ') { count++; } } } } if(s.charAt(0)==' ') { count--; } return count+1; } }