LeetCode58. 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
解析:
根据给定的字符,返回最后一个单词的长度。
方法1
[cc lang=”C++”]
class Solution {
public:
int lengthOfLastWord(string s) {
int index = s.find_last_not_of(‘ ‘);
return index == -1 ? 0 : index – s.find_last_of(‘ ‘, index);
}
};
[/cc]
方法2
[cc lang=”C++”]
C++
class Solution {
public:
int lengthOfLastWord(const char *s) {
int len = strlen(s);
while (–len >=0 && s[len] == ‘ ‘);
len++;
int i = len;
while (i >= 0){
if (s[–i] == ‘ ‘)
break;
}
if (i < 0)
return len;
return len - i - 1;
}
};
[/cc]