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 ' '.
My Solution
To solve this problem, we can use the Java String split method to split the string based on white spaces. Then we iterate through the resulting array and if the element is not empty we increment the number of segments. We return the number of segments in the end.
Time complexity is O(n), where n is the length of the string because of the split method and our pass through the resulting array where we find the number of non-whitespace segments. Space complexity is O(n) due to the array generated by the split method.
class Solution {
public int countSegments(String s) {
String[] arr = s.split(" ");
int n = arr.length;
int segments = 0;
for (String str : arr) {
if (str.length() != 0) {
segments++;
}
}
return segments;
}
}