这题较易,但陷阱也不少。
我的解法是把string s倒置过来,找第一个非空字符串。
注意:
1) "a "的情况。此时要用一个while()遍历所有的空格。
2) " "的情况,此时要注意pos不能超界。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int lengthOfLastWord(string s) {
if (!s.size()) return 0;
string s_orig(s);
reverse(s.begin(), s.end());
size_t pos = s.find(' ');
if (pos==string::npos) return (int)(s_orig.size());
else if (pos==0) { //for the case of "a " or "a "
while((pos<s.size()-1) && (s.at(++pos)==' ')); //pos<s.size() is for the case of " "
size_t pos2 = s.find(' ', pos);
if (pos2==string::npos) return s.size()-pos;
else return pos2-pos;
}
else
return (int)pos;
}
int main()
{
string input_s="Hello World";
cout<<lengthOfLastWord(input_s)<<endl;
input_s="a ";
cout<<lengthOfLastWord(input_s)<<endl;
input_s=" ";
cout<<lengthOfLastWord(input_s)<<endl;
return 0;
}