华为机试-1 字符串最后一个单词的长度
字符串最后一个单词的长度
http://www.nowcoder.com/questionTerminal/8c949ea5f36f422594b306a2300315da
题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
示例1
输入
hello world
输出
5
解题思路
从后往前遍历
因为题目要求最后一个单词长度,我们如果从前往后遍历的话,假设长度为5000,会多余话费大量的时间,所以很明显我们可以从后往前遍历,直到遇到第一个空格为止。
如何找到字符串的尾部
如何寻找字符串末尾呢?可以用strlen( )函数,我这边考虑自己实现strlen( )。如何实现呢?可以直接遍历整个字符串,直到遇到'\0'为止,得到字符串长度idx,并用sp[idx-1]表示字符串的尾部。
c语言实现
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* sp;
int idx = 0;
int count = 0;
sp = (char*)malloc(sizeof(char)*5000);
gets(sp);
while (sp[idx] != '\0')
{
idx++;
}
for (int i = idx-1; i >= 0; i--)
{
if (sp[i] != ' ')
{
count++;
}
else
{
break;
}
}
printf("%d\n",count);
free(sp);
return 0;
} c++实现
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
while (getline(cin,str))
{
int count = 0;
for (int i = str.size()-1; i >= 0; i-- )
{
if (str[i] != ' ')
{
count++;
}
else{
break;
}
}
cout << count << endl;
}
return 0;
} 
