This is the 8th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.
preface
You are given a string s, consisting of several words separated by space characters. Returns the length of the last word in the string.
A word is the largest substring that consists only of letters and does not contain any space characters.
Their thinking
To get the length of the last word, we can iterate from back to front. If we meet a space, the last word is completed
Note that there are whitespace before and after the string. You can call the trim() method on the string to remove whitespace before and after the string
class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int res = 0;
int len = s.length();
char tmp = 'a';
for (int i = len - 1; i >= 0; i--) {
tmp = s.charAt(i);
if (tmp == ' ') break;
res++;
}
returnres; }}Copy the code
Other ideas
Tags: String traversal starts at the end of the string and moves forward, and there are two main cases where the first case, for example, the string “Hello World”, moves backwards until it reaches the end or reaches a space, which is the length 5 of the last word “World” and the second case, Take the string “Hello World” for example, you need to filter out the Spaces at the end of the string, and then do the first operation, which is to consider the last word to be “World” with a length of 5, so the whole process is to filter out the Spaces from the back to find the end of the word, and then walk forward from the end to find the head of the word, and then subtract the two. Time complexity: O(n), where n is the final space and the total length of the final word
conclusion
- There should be no difficulty in this question, we just need to look backwards. It is clearly mentioned in the question that the identification of each word is separated by Spaces, and it does not ask us to add semantic analysis. Of course, adding semantics is not related to the exam algorithm.
Feel free to like it