Description:
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. 先把字符串最后面的空格全部去掉,然后再返回最后一个单词的长度。
代码如下:
class Solution { public: int lengthOfLastWord(string s) { int count = 0; int i = s.length() - 1, j; while(s[i] == ' ') i --; for (j = i; j >= 0; j --) { if(s[j] == ' ') break; } return i-j; } };
代码如下:
class Solution { public: int lengthOfLastWord(string s) { stringstream ss(s); string tmp; int length = 0; while(getline(ss, tmp, ' ')) { if (!tmp.empty()) { length = tmp.size(); } } return length; } };