434.文字列内の単語数(java)


           ,                  。

   ,                     。

  :

  : "Hello, my name is John"
  : 5

  :  (LeetCode)
  :https://leetcode-cn.com/problems/number-of-segments-in-a-string
          。           ,          。

解法一
class Solution {
     
    public int countSegments(String s) {
     
        if(s.length() == 0) return 0;
        String[] words = s.split("\\s+");
        int len = words.length;
        if(len == 0) return 0;
        if(words[0].equals("")) len--;
        if(words[words.length-1].equals("")) len--;
        return len;
    }
}

解法二
class Solution {
     
    public int countSegments(String s) {
     
        if(s.length() == 0) return 0;
        char[] words = s.toCharArray();
        int count = 0;
        if(words[0] != ' ') count++; 
        for(int i = 1; i < s.length(); i++){
     
            if(words[i-1]==' ' && words[i]!=' ') count++;
        }
        return count;
    }
}