LeetCode 434-the number of words in the string

1. Topic introduction

Count the number of words in a string, where words refer to consecutive characters that are not spaces.

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

Example:

Input: "Hello, my name is John"
Output: 5
Explanation: The word here refers to consecutive characters that are not spaces, so "Hello," counts as 1 word.

Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-segments-in-a-string The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

This question only needs to perform special treatment on the space character, see the code for details.

Three, problem-solving code

class Solution {
public:
    int countSegments(string s) {
        int cnt = 0;
        int n = s.size();
        int i = 0;
        while(i < n)
        {
            if(s[i] == ' ')
            {
                i++;
                continue;
            }
            while(i < n && s[i] != ' ')
                i++;
            cnt++;
        }
        return cnt;
    }
};

Four, problem-solving results

 

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/113123808