Number Of Segments In A String Problem


Description

LeetCode Problem 434.

You are given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

Example 1:

1
2
3
Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

1
2
Input: s = "Hello"
Output: 1

Example 3:

1
2
Input: s = "love live! mu'sic forever"
Output: 4

Example 4:

1
2
Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 300
  • s consists of lower-case and upper-case English letters, digits or one of the following characters “!@#$%^&*()_+-=’,.:”.
  • The only space character in s is ‘ ‘.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    int countSegments(string s) {
        int seg = 0;
        char lastc = ' ';
        for (char c : s) {
            if ((lastc == ' ') && (c != ' ')) {
                seg ++;
            }
            lastc = c;
        }
        return seg;
    }
};




Related Posts

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...