2019.1.16
题目描述:
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
这题是求最后一个单词的长度,但是需要注意一个“陷阱”,如果字符串某一个单词之后全是空格,则这就是最后一个单词了,比如说“a ”,那最后一个单词的长度就是1。
解法一:我们要先对字符串进行处理,去除字符串最后的连续空格,再将字符串从后往前遍历到第一个空格,则刚刚扫描的就是最后一个单词,长度就是该单词的长度。
C++代码:
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.size()==0) return 0;
int k=0,i=s.size()-1;
while(s[i]==' ') --i;
while(s[i]!=' '&&i>=0){
k++;
i--;
}
return k;
}
};
执行时间:4ms
解法二:
也可以从前往后遍历,遍历字符串的时候,如果遇到非空格的字符,我们只需要判断其前面一个位置的字符是否为空格,如果是的话,那么当前肯定是一个新词的开始,将计数器重置为1,如果不是的话,说明正在统计一个词的长度,计数器自增1即可。但是需要注意的是,当i=0的时候,无法访问前一个字符,所以这种情况要特别判断一下,归为计数器自增1那类。
C++代码:
class Solution {
public:
int lengthOfLastWord(string s) {
int res = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] != ' ') {
if (i != 0 && s[i - 1] == ' ') res = 1;
else ++res;
}
}
return res;
}
};