您的位置:首页 > 其它

Length of Last Word

2013-06-16 17:37 295 查看
Q: 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
.

A: length记录当前单词长度(空格看做长度为0),prevLength记录(前一个单词长度)。

如果length>0, 最后一个单词长度为length,否则为prevLength;

给prevLength赋值的时候要考虑空格连续的情况:如果length = 0, 说明遇到连续空格,不应该给prevLength赋值。

int lengthOfLastWord(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int length = 0;
int  prevLength = 0;
const char *cur = s;
while(*cur!='\0')
{
if(*cur!=' ')
length++;
else
{
prevLength = (length>0?length:prevLength);
length = 0;
}

cur++;
}

return (length>0?length:prevLength);
}


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