您的位置:首页 > 其它

LeetCode58----Length of Last Word

2015-09-07 17:00 411 查看
LeetCode敲的第一题,小菜鸟一只,纪念一下~~

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) {
const char *p=s.c_str();
if(*p=='\0')<span style="white-space:pre">	</span>//判断字符串是否为空
{
return 0;
}
int num=0;
while(*p!='\0')<span style="white-space:pre">		</span>//判断是否为字符串尾
{
if(*p!=' ')<span style="white-space:pre">		</span>//不是空格时计数
{
num++;
p++;
}
else
{
if(*(++p)!='\0'&&*p!=' ')<span style="white-space:pre">	</span>//空格时,判断下一字符是否为串尾,并是否为连续空格,
num=0;<span style="white-space:pre">		</span>//不是串尾&&不是空格,表明为字符,重新计数;否则,进行新一轮判断

}

}
return num;

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