Powered By GitBook
58.Length of Last Word

58.Length of Last Word

难度:Easy
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.
1
Example:
2
3
Input: "Hello World"
4
Output: 5
Copied!
从后面开始判断,求出最后一个单词的长度。
1
class Solution {
2
public:
3
int lengthOfLastWord(string s) {
4
int len=0;
5
for(int i=s.length()-1;i>=0;i--)
6
{
7
if(s[i] == ' ' && len ) break;
8
else if(s[i] !=' ') len++;
9
10
}
11
return len;
12
}
13
};
Copied!
执行用时 :4 ms, 在所有 C++ 提交中击败了86.57%的用户 内存消耗 :8.7 MB, 在所有 C++ 提交中击败了82.08%的用户
Last modified 2yr ago
Copy link