您的位置:首页 > 其它

leetcode——Length of Last Word

2014-12-11 22:04 441 查看
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
.

#include<iostream>
//#include <string>
using namespace std;

int lengthOfLastWord(const char *s)
{
int length_s=strlen(s);

if(length_s==0)//考虑空字符串的情况
return 0;
//if(length_s==1&&s[0]!=' ')//考虑只有一个不是空格的字符串
// return 1;
int a,b;
for(a=length_s-1;a>=0;a--)//先找出第一个不为空的地方
{
if(s[a]!=' ')
break;
}
if(a==0&&s[0]==' ')//也许全部为空
return 0;
for(b=a;b>=0;b--)//在找到第一个不为空的位置后,接着找之后第一个为空的位置
{
if(s[b]==' ')
break;
}
return a-b;
}
int main()
{
char* s="a ";
cout<<strlen(s)<<endl;
cout<<lengthOfLastWord(s)<<endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: