【题目描述】
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.
【解题思路】这道题其实很简单,只要换个角度从右边开始扫描,分别找到最后一个word的开端和结尾的位置就可以了,但因为一些细节上的问题wa了好几次,考虑的还是不全面。
要注意的是:1、可能最后一个word的右边还有空格 2、会出现全是空格的情况。
【代码】
class Solution {
public:
int lengthOfLastWord(string s) {
int len=s.size();
int pos=len-1;
int i;
if(len==0) return 0;
for(i=len-1;i>=0;i--){
if(s[i]!=' '){
pos=i;
break;
}
}
for(i=pos;i>=0;i--){
if(s[i]==' '){
break;
}
}
return pos-i;
}
};
我的ac代码耗时是4ms,在discuss里看到有人是0ms,思路是一样的,主要是将for循环改成了while循环,while循环因为比for循环少了一步,所以速度会更快一点。
int lengthOfLastWord(char* s) {
int lastLen = 0;
char* p = s + strlen(s) -1;
while(p>=s && isspace(*p)) p--;
while(p>=s && !isspace(*(p--))) lastLen++;
return lastLen;
}