title: Daily practice (38): the length of the last word
categories:[Swords offer]
tags:[Daily practice]
date: 2022/04/09
Daily practice (38): The length of the last word
You are given a string s consisting of several words separated by some space characters before and after them. Returns the length of the last word in the string.
A word is the largest substring consisting of only letters and not containing any space characters.
Example 1:
Input: s = "Hello World"
output: 5
Explanation: The last word is "World" and has a length of 5.
Example 2:
Input: s = "fly me to the moon"
output: 4
Explanation: The last word is "moon" and has a length of 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" of length 6.
hint:
1 <= s.length <= 104
s only consists of English letters and spaces ' '
there is at least one word in s
Source: LeetCode
Link: https://leetcode-cn.com/problems/length-of-last-word
Method 1: Double pointer method
Thought analysis
Define two pointers to point to the end of the string, if the end of the string is a space, the pointers move forward at the same time i--; j--;
If a non-space is encountered, then the fixed j does not move, indicating the end of the word, and continues to move forward i until a space is encountered again, or the string is traversed;
Finally, the position pointed to by i is the position before the beginning of the last word, and j - i is the length of the last word.
int lengthOfLastWord(string s) {
int i = s.size() - 1; //定义两个指针指向字符串的末尾
int j = i;
while (s[i] == ' ') {
i--;
j--;
}
//此时i,j指向最后一个单词的末尾位置
while (i >= 0 && s[i] != ' ') {
i--;
}
return j - i; //得到最后一个单词的长度
}
Method 2: Reverse Traversal
Thought analysis
Continue traversing the string in reverse, starting at the last letter, until a space is encountered or the beginning of the string is reached. Each letter traversed is a letter in the last word, so the number of letters traversed is
the length of the last word
int lengthOfLastWord(string s) {
int index = s.size() - 1;
while (s[index] == ' ') {
index--;
}
//此时index指向最后一个字符串的的末尾
int wordLength = 0;
while (index >= 0 && s[index] != ' ') {
wordLength++; //通过遍历得到最后一个字符串的长度
index--;
}
return wordLength;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。