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
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 =
return
#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;
}
' ', 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;
}
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Length of Last Word
- [LeetCode] Length of Last Word
- leetcode Length of Last Word
- LeetCode | Length of Last Word
- LeetCode_Length Of Last Word
- 【LeetCode with Python】 Length of Last Word
- [leetcode]Length of Last Word
- LeetCode - Length of Last Word
- leetcode: Length of Last Word
- LeetCode_Length of Last Word
- LeetCode Length of Last Word
- leetcode 21: Length of Last Word
- leetcode 21: Length of Last Word
- leetcode:Length of Last Word
- [Leetcode 3] 58 Length of Last Word
- LeetCode: Length of Last Word
- [leetcode] Length of Last Word
- [LeetCode] Length of Last Word
- [leetcode]Length of Last Word
- [leetcode]Length of Last Word