题目:
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Input: "Hello World" Output: 5
代码:
方法一:把每个值都存了
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.length();
if (len == 0)return 0;
vector<string> words;
for (int i = 0; i < len; i++) {
if (s[i] == ' ')continue;
string word = "";
while (i < len&&s[i] != ' ') {
word.push_back(s[i]);
i++;
}
words.push_back(word);
}
if (words.size()==0)return 0;
return words.back().length();
}
};
方法二:只记最后一个。
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.length();
if (len == 0)return 0;
int reslen=0;
for (int i = len-1; i >=0; i--) {
if (s[i] == ' ')continue;
while (i>=0&&s[i] != ' ') {
reslen++;
i--;
}
break;
}
return reslen;
}
};
想法:学会创新