ADV-78-算法提高-最长单词
2017-04-06 20:12
183 查看
算法提高 最长单词
编写一个函数,输入一行字符,将此字符串中最长的单词输出。
输入仅一行,多个单词,每个单词间用一个空格隔开。单词仅由小写字母组成。所有单词的长度和不超过100000。如有多个最长单词,输出最先出现的。
样例输入
I am a student
样例输出
student
#include <iostream>
using namespace std;
int main() {
char str[] = " today is saturday is it";//存储字符串
int count = 0, maxcount = 0 , maxstr = 0 ;//count存储单词长度
//maxcount存储最大单词长度,maxstr存储最大单词第一个字符初始位置
int i = 0;//i存储字符的位置
while (str[i] != '\0') { // '\0'表示字符长结束
if (str[i] != ' ') {
count ++; //如果没有遇到空格,count储存的单词长度+1
}
if (str[i] == ' ') {
count = 0; //如果遇到空格,单词长度清零
}
i++;
if (maxcount < count ) {
maxcount = count; //找出最长单词长度
maxstr = i - maxcount; //最大单词第一个字符初始位置
}
}
for (int j = maxstr; j < maxstr + maxcount; j++) {
printf("%c",str[j]); //输出最长单词
}
return 0;
}
编写一个函数,输入一行字符,将此字符串中最长的单词输出。
输入仅一行,多个单词,每个单词间用一个空格隔开。单词仅由小写字母组成。所有单词的长度和不超过100000。如有多个最长单词,输出最先出现的。
样例输入
I am a student
样例输出
student
#include <iostream>
using namespace std;
int main() {
char str[] = " today is saturday is it";//存储字符串
int count = 0, maxcount = 0 , maxstr = 0 ;//count存储单词长度
//maxcount存储最大单词长度,maxstr存储最大单词第一个字符初始位置
int i = 0;//i存储字符的位置
while (str[i] != '\0') { // '\0'表示字符长结束
if (str[i] != ' ') {
count ++; //如果没有遇到空格,count储存的单词长度+1
}
if (str[i] == ' ') {
count = 0; //如果遇到空格,单词长度清零
}
i++;
if (maxcount < count ) {
maxcount = count; //找出最长单词长度
maxstr = i - maxcount; //最大单词第一个字符初始位置
}
}
for (int j = maxstr; j < maxstr + maxcount; j++) {
printf("%c",str[j]); //输出最长单词
}
return 0;
}
相关文章推荐
- 算法提高 ADV-78 最长单词
- 蓝桥杯 ADV-78 算法提高 最长单词
- 蓝桥杯 ADV-78 算法提高 最长单词
- 蓝桥杯 ADV-78 算法提高 最长单词
- 算法提高 最长单词
- 算法提高 最长单词&&单词个数统计&&不同单词个数统计
- 蓝桥杯ADV-17算法提高 统计单词数
- 蓝桥杯 ADV-102 算法提高 单词个数统计
- 蓝桥杯 算法提高VIP 最长单词(Java解题)
- 蓝桥杯 ADV-102 算法提高 单词个数统计
- 算法提高 ADV-17 统计单词数
- 蓝桥杯 ADV-105 算法提高 不同单词个数统计
- 算法提高 ADV-105 不同单词个数统计
- 【ShawnZhang】带你看蓝桥杯——算法提高 最长单词
- 算法提高 ADV-207 最长字符序列
- 算法提高----最长单词
- ADV-102 算法提高 单词个数统计
- FCC算法:四、Find the Longest Word in a String -- 找出最长单词
- 蓝桥杯 ADV-20 算法提高 交换Easy
- 蓝桥杯 ADV-76 算法提高 GDP计算