Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.
A word is a maximal substring consisting of non-space characters only.
Input: s = "Hello World"
Output: 5
Input: s = " "
Output: 0
- 1 <= s.length <= 10^4
- s consists of only English letters and spaces ' '.
- java
/*
Success Detail:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
Memory Usage: 36.4 MB, less than 98.02% of Java online submissions for Length of Last Word.
*/
class Solution {
public int lengthOfLastWord(String s) {
int right = s.length() - 1;
while (right >= 0 && s.charAt(right) == ' ') {
right--;
}
if (right < 0) {
return 0;
}
int left = right;
while (left >= 0 && s.charAt(left) != ' ') {
left--;
}
return right - left;
}
}