0058 Length of Last Word
问题概述
解题思路
class Solution
{
public:
int lengthOfLastWord(std::string s)
{
reverse(s.begin(), s.end());
// std::cout << s << std::endl;
int index = 0;
while (s[index] == ' ')
{
index++;
}
int start = index;
while (s[index] != ' '&& s[index] != '\0')
{
index++;
}
return index - start;
}
};
class Solution
{
public:
int lengthOfLastWord(std::string s)
{
int n = (int)s.size();
int cnt = 0;
for (int i = n - 1; i > -1; --i)
{
if (s[i] != ' ') { ++cnt; }
else if (cnt != 0) { break; }
}
return cnt;
}
};