您的位置:首页 > 其它

LeetCode *** 58. Length of Last Word

2016-04-10 11:00 477 查看
题目:

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.

For example,

Given s =
"Hello World"
,

return
5
.

分析:

如果有一个单词,那么必定是以‘空格+符号’的形式开始单词或者整个字符串都是一个单词的形式存在的。那么直接判断最后一次出现这种形式是什么时候即可。

代码:

class Solution {
public:
int lengthOfLastWord(string s) {

int length=s.length();
if(length==0)return 0;

int last=0;

int i;
for(i=1;i<length;++i)
if(s[i]!=' '&&s[i-1]==' '){
last=i;
}

i=last;
int res=0;
while(s[i]!=' '&&i<length){
res++;i++;
}

return res;
}
};


合在一起:
class Solution {
public:
int lengthOfLastWord(string s) {

int length=s.length();
if(length==0)return 0;

int last=0,res=0,lastI=last;

for(int i=1;i<length;++i){

if(s[lastI++]!=' ')res++;

if(s[i]!=' '&&s[i-1]==' '){
last=i;
lastI=last;
res=0;
}
}

if(s[length-1]!=' ')res++;

return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: