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]

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据