class Solution {
public:
int lengthOfLastWord(string s)
{
if(s=="")
return 0;
if(s==" ")
return 0;
size_t pos = s.find_last_of(" ");
if(pos != string::npos)
{
string sub = s.substr(pos);
return sub.length();
}
else
return s.length();
}
};
What is wrong with the following code?

so many bad cases, for example, if the string like "abc ", there are one space at last position, the answer of your algorithm is wrong.
My C++ solution:
 Firstly, remove all spaces at tail
 From the last nonspace to start, calculate the length and end the algorithm if the character is space
================================================
class Solution { public: int lengthOfLastWord(string s) { if(s == "") return 0; int index = s.length()  1; for(int i = s.length()  1; i >= 0; i) if(s[i] != ' '){ index = i; break; } int ret = 0; for(int i = index; i >= 0; i){ if(s[i] == ' ') break; ret++; } return ret; } };