LeetCode 0434. Number of Segments in a String Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0434. Number of Segments in a String

Description

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 ' '.

Solutions

Solution 1: String Splitting

We split the string s by spaces and then count the number of non-empty words.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the string s.

PythonJavaC++GoTypeScriptPHP
class Solution: def countSegments(self, s: str) -> int: return len(s.split())(code-box)

Solution 2: Simulation

We can also directly traverse each character s[i] in the string. If s[i] is not a space and s[i-1] is a space or i = 0, then s[i] marks the beginning of a new word, and we increment the answer by one.

After the traversal, we return the answer.

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).

PythonJavaC++GoTypeScriptPHP
class Solution: def countSegments(self, s: str) -> int: ans = 0 for i, c in enumerate(s): if c != ' ' and (i == 0 or s[i - 1] == ' '): ans += 1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !