434. Number of Segments in a String

  • Difficulty: Easy

  • Topics: String

  • Similar Questions:

Problem:

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: "Hello, my name is John"
Output: 5
</p>

Solutions:

class Solution {
public:
    int countSegments(string s) {
        if (s.length() == 0)    return 0;
        int pos = 1;
        int count = (s[0] == ' ' ? 0 : 1);
        while (pos < s.length()) {
            if (s[pos] != ' ' && s[pos-1] == ' ')   ++count;
            ++pos;
        }
        return count;
    }
};

results matching ""

    No results matching ""