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
- Problem Statement
- Complexity Analysis
- Number of Segments in a String solution in C++
- Number of Segments in a String solution in Java
- Number of Segments in a String solution in Python
- Additional Resources
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
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.