[Lc]58最后一个单词的长度
Contents
题目
题解
- 时间复杂度$O(k)$, k为最后一个单词的长度。
- 空间复杂度$O(1)$
从后往前遍历,开始的0全部跳过,然后计数,再次遇到0跳出循环
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.size();
int res = 0;
while(n--){
if(s[n]==' ' && res==0) continue;
if(s[n]==' ' && res!=0) break;
res++;
}
return res;
}
};
Author ChrisHRZ
LastMod 2020-05-05