lc434.字符串中的单词数
            
               约 122 字 
                 预计阅读 1 分钟 
         
实现split
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
  | 
class Solution {
public:
    int countSegments(string s) {
        int cnt = 0;
        for(int i = 0, j = 0; j < s.size(); ) {
            if(s[j] != ' ') {
                while(s[j] != ' ' && j < s.size()) {
                    j ++;
                }
                cnt += 1;
            } else {
                j ++;
                i = j;
            }
        }
        return cnt;
    }
};
  | 
 
1
2
3
  | 
class Solution:
    def countSegments(self, s: str) -> int:
        return len([w for w in s.split(" ") if w != ""])
  |