434. Number of Segments in a String LeetCode Solution

In this guide, you will get 434. Number of Segments in a String LeetCode Solution with the best time and space complexity. The solution to Number of Segments in a String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Number of Segments in a String solution in C++
  4. Number of Segments in a String solution in Java
  5. Number of Segments in a String solution in Python
  6. Additional Resources
434. Number of Segments in a String LeetCode Solution image

Problem Statement of Number of Segments in a String

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:

Input: s = “Hello, my name is John”
Output: 5
Explanation: The five segments are [“Hello,”, “my”, “name”, “is”, “John”]

Example 2:

Input: s = “Hello”
Output: 1

Constraints:

0 <= s.length <= 300
s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".
The only space character in s is ' '.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

434. Number of Segments in a String LeetCode Solution in C++

class Solution {
 public:
  int countSegments(string s) {
    int ans = 0;

    for (int i = 0; i < s.length(); ++i)
      if (s[i] != ' ' && (i == 0 || s[i - 1] == ' '))
        ++ans;

    return ans;
  }
};
/* code provided by PROGIEZ */

434. Number of Segments in a String LeetCode Solution in Java

class Solution {
  public int countSegments(String s) {
    int ans = 0;

    for (int i = 0; i < s.length(); ++i)
      if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' '))
        ++ans;

    return ans;
  }
}
// code provided by PROGIEZ

434. Number of Segments in a String LeetCode Solution in Python

class Solution:
  def countSegments(self, s: str) -> int:
    return len(s.split())
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.