[String-easy] 434. Number of Segments in a String returns a given string how many words. Words are separated by spaces

1. The title site

https://leetcode.com/problems/number-of-segments-in-a-string/

2. Title Description

Here Insert Picture Description

3. subject to the effect

Returns the given string how many words. Words are separated by spaces.

4. Problem-solving ideas

Sign problem

5. AC Code

class Solution {
    public int countSegments(String s) {
            int count = 0;
    for (int i = 0; i < s.length(); ++i)
        if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' '))
            ++count;
    return count;
    }
}

Guess you like

Origin blog.csdn.net/xiaojie_570/article/details/92606859