topic
Given a string s containing only uppercase and lowercase letters and spaces'', return the length of its last word. If the string scrolls from left to right, then the last word is the last word that appears.
If there is no last word, please return 0.
Note: A word refers to the largest substring that consists of only letters and does not contain any space characters.
answer
This question considers how to find the last consecutive string that does not contain null characters. How do you find such a word? In fact, we only need to find the beginning and end of the string to be found. Since it is to find in a string, it is inevitable to traverse. First consider traversing from the beginning. We found that it is not easy to determine the beginning of the last word. When traversing to a word, if you don’t know the characters behind it, it’s not sure if it is the last one. Then consider traversing from back to front, and find that it is easier to determine the last word. The first non-blank character encountered when traversing from back to front is the end of the last word. Continue to traverse and find the beginning of the word when it encounters the first null character.
In addition, consider the case where the length of the string is 0, and the case where there is no word in the entire string.
Code
class Solution {
public int lengthOfLastWord(String s) {
if(s.length() == 0) {
return 0;
}
int end = s.length() - 1;
while(end >= 0 && s.charAt(end) == ' ') {
end--;
}
int start = end;
while(start >= 0 && s.charAt(start) != ' ') {
start--;
}
return end - start;
}
}