0
点赞
收藏
分享

微信扫一扫

58. Length of Last Word*

58. Length of Last Word*

​​https://leetcode.com/problems/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

题目思路

先找到最后一个单词, 将末尾的空格过滤, 从后向前统计最后一个 ​​word​​​ 的长度. 或者使用 ​​stringstream​​.

C++ 实现 1

class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0, j = s.size() - 1;
while (j >= 0 && s[j] == ' ') j --;
while (j >= 0 && s[j] != ' ') {
count ++;
j --;
}
return count;
}
};

C++ 实现 2

class Solution {
public:
int lengthOfLastWord(string s) {
stringstream ss(s);
string word;
while (ss >> word);
return word.size();
}
};


举报

相关推荐

0 条评论