058.Length of Last Word

Test cases

1
2
3
4
5
6
""
"Hello World"
"OneWord"
"Space "
" Space"
"b a "

Solution 1: accepted 5ms

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

1
2
3
4
5
6
7
8
9
10
11
public int lengthOfLastWord(String s) {
s = s.trim();
int len = s.length();
for(int i = len - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
return len - i- 1;
// return s.substring(i + 1, len).length(); // improved
}
}
return len == 0? 0 : len;
}

Other solutions

1
2
3
public int lengthOfLastWord(String s) {
return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int lengthOfLastWord(String s) {
String s1 = s.trim();
int count = 0;
for(int i = s1.length() - 1; i >=0; i--){
if (s1.charAt(i) != ' '){
count ++;
}
else{
break;
}
}
return count;
}
}