#include<cstring>
using namespace std
const int maxn=100 //这个表示单词可能的最大个数
const int maxl=100 //这个表示单词可能的最长长度,需要根据题目要求确定
int n,maxlen
int len[maxn]
char ch[maxn][maxl]
int max(int a,int b){
return a>b?a:b
}
int main(){
int k=0
while(~scanf("%c",&ch[n][k])){ //每次输入一个字符,n表示当前是第几个单词,k表示是这个单词的第几个字母
if(ch[n][k]!=' ' && ch[n][k]!='\n'){ //不是空格或空行说明还没有读完,k++,接着读下一个
k++continue
}
len[n]=k-1 //计算这个单词的长度
maxlen=max(maxlen,len[n]) //更新最长的单词长度
if(ch[n][k]==' ') k=0,n++ //如果读到空格,说明这个单词读完了
else{ //如果读到空行,说明这组数据读完了,开始输出这组数据的答案
for(int i=0i<=ni++)
if(len[i]==maxlen) //如果长度等于最长的单词长度,这个单词就是最长单词
printf("%s",ch[i]) //输出即可
putchar('\n')
memset(ch,0,sizeof(ch)) //将原来的数组清空
n=0maxlen=0k=0
}
}
return 0
}
我自己测了一组输入数据,答案应该没什么问题了:
Hello sir are you satisfied with my answer ?Yes I feel thankful of your answer .
How does it feel ?
It feels very good !
输出:
satisfiedthankful
does feel
feels
等等,我才发现是按字典序输出...我这是按输入顺序输出的....
#include<cstdio>#include<cstring>
#include<algorithm>
using namespace std
const int maxn=100 //这个表示单词可能的最大个数
const int maxl=100 //这个表示单词可能的最长长度,需要根据题目要求确定
int n,maxlen
struct Word{
int len
char ch[maxl]
void clean(){
memset(ch,0,sizeof(ch))
}
}word[maxn]
int max(int a,int b){
return a>b?a:b
}
bool cmp(const Word &a,const Word &b){//比较两个单词的函数
return strcmp(a.ch,b.ch)<0
}
int main(){
int k=0
while(~scanf("%c",&word[n].ch[k])){ //每次输入一个字符,n表示当前是第几个单词,k表示是这个单词的第几个字母
if(word[n].ch[k]!=' ' && word[n].ch[k]!='\n'){ //不是空格或空行说明还没有读完,k++,接着读下一个
k++continue
}
word[n].len=k-1 //计算这个单词的长度
maxlen=max(maxlen,word[n].len) //更新最长的单词长度
if(word[n].ch[k]==' ') k=0,n++ //如果读到空格,说明这个单词读完了
else{ //如果读到空行,说明这组数据读完了,开始输出这组数据的答案
sort(word,word+n+1,cmp) //将所有单词按照字典序排序
for(int i=0i<=ni++)
if(word[i].len==maxlen) //如果长度等于最长的单词长度,这个单词就是最长单词
printf("%s",word[i].ch) //输出即可
putchar('\n')
for(int i=0i<=ni++)
word[i].clean() //将原来的数组清空
n=0maxlen=0k=0
}
}
return 0
}
上面这个是修改稿。
测试数据:
Hello sir are you satisfied with my answer ?Yes I feel thankful of your answer .
How does it feel ?
It feels very good !
What feel it does ?
输出结果:
satisfiedthankful
does feel
feels
What does feel
最后一个What先输出不是错误哦...
因为W是大写...所以字典序比其他的小
//方便起见,我所有注释都用C++的注释符char sentence[82]
int value[82]
int sum[82]
char word[21]
int max=0
int maxplace=-1
gets(sentence)
int i
for(i=0i<strlen(sentence))
{
if( (sentence[i]>='a' && sentence[i]<='z') || (sentence[i]>='A' && sentence[i]<='Z') )
{
value[i]=1
}
else
{
value[i]=0
}
}
//上述操作把是字母的赋值为1,不是字母的赋值为0,结果存放在value数组中
//剩下的工作就是找出最多连续的1,并读取sentence中的原值。
//再进行一步简化操作,求数组value的连续和,
//也就是说,当第i+1位与第i位的值相同时,i+1位存i+1内的值与i位的和之和。
//否则i+1位存他本身的值。
for(i=0i<strlen(sentence)i++)
{
if(i==0)
{
sum[i]=value[i]
}
else if(value[i]==value[i-1])
{
sum[i]=sum[i-1]+value[i]
}
else
{
sum[i]=value[i]
}
}
//找出最大值,就是你需要的单词的末位。想不明白可以找个例子求一下sum数组,一目了然
for(i=0i<strlen(sentence)i++)
{
if (sum[i]>max) //此处填>,就是求出第一个最大长度的,填>=,就是求最后一个最大长度的
{
max=sum[i]
maxplace=i-max+1 //直接求出单词的首字母,配合长度max,很容易找出单词
}
}
for(i=0i<maxi++) word[i]=sentence[maxplace+i]
word[i]='\0'
printf("%s\n",word)