LeetCode 58.
Tags: LeetCode
Complexity
-
Time complexity: O(n)
-
Space complexity: O(1)
Code
class Solution {
public int lengthOfLastWord(String s) {
int ind = s.length();
int left = 0, right = -1;
while (--ind >= 0) {
if (s.charAt(ind) != ' ') {
right = ind;
break;
}
}
ind = right;
while (--ind >= 0) {
if (s.charAt(ind) == ' ') {
left = ind + 1;
break;
}
}
return right - left + 1;
}
}
Check out the description of this problem at LC 58.