题目:
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.
For example,
Given s = "Hello World"
,
return 5
.
思路:
Easy级别的题目,没有什么技巧而言,只需要处理好两种特殊情况:1)字符串为空;2)字符串全部由空格组成。时间复杂度为O(n)。
代码:
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.length() == 0)
return 0;
int i = s.length() - 1;
while(i >= 0 && s[i] == ' ') // ignoring the tailing spaces
--i;
if(i < 0) // s consists of all spaces
return 0;
int ret = 0;
while(i >= 0 && s[i] != ' ')
{
++ret;
--i;
}
return ret;
}
};