58. Length of Last Word
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
思路
比较简单,求最后一个字符的长度,先得到最后一个非空字符的位置,再得到最后一个词前面一个空格的位置,两个位置的index值相减即得到最后一个词的位置。
代码
class Solution {
public:
int lengthOfLastWord(string s) {
int end = s.find_last_not_of(' ');
return end == string::npos ? 0 : (end - s.find_last_of(' ', end));
}
};