leetcode 434. Number of Segments in a String

class Solution {
public:
    int countSegments(string s) {
        int ans = 0,flag = 0;
        for(int i = 0;i < s.length(); i++){
            if(s[i] == ' '){
                ans += flag;
                flag = 0;
            }
            else {
                flag = 1;
            }
        }
        ans += flag;
        return ans;
    }
};

你可能感兴趣的:(##笔试类编程题)