1. 题目来源
2. 题目解析
简单题,做法很多。stringstream
可以做。正常的就是双指针做法了,也是经典的处理以空格间隔的输入数据的一种方式。注意尾部的连续空格即可。最优的还是双指针从后往前遍历。
- 时间复杂度: O ( n ) O(n) O(n)。
- 空间复杂度: O ( 1 ) O(1) O(1)
代码:
// 双指针,从前往后遍历
class Solution {
public:
int lengthOfLastWord(string s) {
int k = s.size() - 1;
while (k >= 0 && s[k] == ' ') k -- ;
int res = 0;
for (int i = 0, j = 0; i <= k; i ++ ) {
j = i;
while (i <= k && s[i] != ' ' ) i ++ ;
res = i - j;
}
return res;
}
};
// 双指针,从后向前遍历
class Solution {
public:
int lengthOfLastWord(string s) {
for (int i = s.size() - 1; ~i; i -- ) {
if (s[i] == ' ') continue;
int j = i - 1;
while (j >= 0 && s[j] != ' ') j -- ;
return i - j;
}
return 0;
}
};
// stringstream
class Solution {
public:
int lengthOfLastWord(string s) {
stringstream ssin(s);
int res = 0;
string word;
while (ssin >> word) res = word.size();
return res;
}
};