Problem
Solutions (time, space)
- using split()
- count word with condition
If the program need to limit the space, should use 2 way. But, normally using split seems better for developing speed.
using split() O(n), O(n)
class Solution {
public int countSegments(String s) {
//String trimmedS=s.trim(); //lower than java 11
String trimmedS=s.strip(); //higher than java 11, it cover more kinds of space
if(trimmedS.equals("")) return 0;
String[] temp = trimmedS.split("\\p{Z}+"); //regex: all possible space+
return temp.length;
}
}
Explanation
- trim first and last space
- split by spaces
- count words
count word with condition O(n), O(1)
class Solution {
public int countSegments(String s) {
int counter = 0;
for (int i = 0; i < s.length(); ++i) {
if ((i == 0 || s.charAt(i - 1) == ' ') && s.charAt(i) != ' ') {
++counter;
}
}
return counter;
}
}
Explanation
loop each Characters with counting word.
word counting condition is
- if current position is not space and previous position is space (s.charAt(i - 1) == ' ') && s.charAt(i) != ' ')
- if current position is not space and previous position is null (for first word) (i == 0 && s.charAt(i) != ' ')