最长最短单词

版权声明:请勿轻易转载 https://blog.csdn.net/weixin_43838723/article/details/84668057

1143:最长最短单词


时间限制: 1000 ms         内存限制: 65536 KB
提交数: 5553     通过数: 1929 

【题目描述】

 输入1行句子(不多于200个单词,每个单词长度不超过100),只包含字母、空格和逗号。单词由至少一个连续的字母构成,空格和逗号都是单词间的间隔。

 试输出第1个最长的单词和第1个最短单词。

【输入】

一行句子。

【输出】

第1行,第一个最长的单词。

第2行,第一个最短的单词。

【输入样例】

I am studying Programming language C in Peking University

【输出样例】

Programming
I

【提示】

提示:

如果所有单词长度相同,那么第一个单词既是最长单词也是最短单词。

【来源】


http://ybt.ssoier.cn:8088/problem_show.php?pid=1143

源代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	char a[23333];
	gets(a);
	
	int len;
	len=strlen(a);
	
	int i;
	int max=-999;
	int maxplace;
	int min=999;
	int minplace;
	int ans=0;
	
	for(i=0;i<len;i++)
	{
		//ans accumulates if the position in the character array is not a space or comma
		if(a[i]!=' '&&a[i]!=',')
		    ans++;
		else if(ans>0)
		{
			//If ans is greater than Max, the length of the word and the initial position of the word are recorded
			if(ans>max)
			{
				max=ans;
				maxplace=i-ans;
			}
			
			//If ans is less than min, record the word length and position
			if(ans<min)
			{
				min=ans;
				minplace=i-ans;
			}
			
			ans=0;
		}   
	}
	
	    //Direct output (output the first word twice if all words are equal in length)
    	for(i=maxplace;i<=maxplace+max-1;i++)
    	    cout<<a[i];
    	cout<<endl; 
		for(i=minplace;i<=minplace+min-1;i++)
		    cout<<a[i];    
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43838723/article/details/84668057