问题描述:
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
题源:here;完整实现:here
思路:
从最后一个位置往前数,直到遇到‘ ’
。当然需要考虑一开始就遇到‘ ’
的情况。实现如下:
class Solution {
public:
int lengthOfLastWord(string s) {
int sLen = s.size();
if (sLen == 0) return 0;
int i = 0, j;
while (s[sLen - i - 1] == ' ' && i < sLen) i++; j = i;
while (!(s[sLen - i - 1] == ' ') && i<sLen) i++;
return i-j;
}
};