1.题目:https://leetcode-cn.com/problems/length-of-last-word/
2.思路
(1)标签:字符串遍历
从字符串末尾开始向前遍历,其中主要有两种情况
第一种情况,以字符串"Hello World"为例,从后向前遍历直到遍历到头或者遇到空格为止,即为最后一个单词"World"的长度5
第二种情况,以字符串"Hello World “为例,需要先将末尾的空格过滤掉,再进行第一种情况的操作,即认为最后一个单词为"World”,长度为5
所以完整过程为先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度
时间复杂度:O(n),n为结尾空格和结尾单词总体长度
(2)核心就是从后往前走,但是遇到不同的数字怎么停,很重要
3.代码
https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/
class Solution {
public:
int lengthOfLastWord(string s) {
int length=s.size()-1;
while (length>=0 && s[length]==' ')
length--;
if (length<0)
return 0;
int left=length;
while (left>=0 && s[left]!=' ')
left--;
return length-left;
}
};