题意是说,给定一段以'E-N-D'结尾的文本,要求从中找出最长的单词。其中,最长的单词只能由英文字符和'-'组成。输出时,请输出该最长单词的小写形式。如果有多个单词都是最长单词,那么输出第一个即可。
解题思路也很明确,一个单词一个单词的判断,拿到单词,看看单词首尾是否有标点、数字等其他字符,如果有,则先掐头去尾,然后再判断单词中间是否也有除了英文字符和'-'之外的字符,如果有,直接跳过。每次判断时,记录下最长的单词,所有单词判断结束时,输出记录的那个最长单词即可。
python版本AC代码
maxlen = 0
longest = ''
maxf = 0
maxt = 0
Running = True
while Running:
sentence = input().split()
sentence_len = len(sentence)
for k in range(sentence_len):
if k == sentence_len -1 and sentence[sentence_len-1] == 'E-N-D':
Running = False
break
word = sentence[k]
word_len = len(word)
len1 = word_len
i = 0
while i < len1 and word[i].isalpha() == False and word[i] != '-':
i += 1
word_len -= 1
f = i
i = len1-1
while i >= 0 and word[i].isalpha() == False and word[i] != '-':
i -= 1
word_len -= 1
t = i
i = f
flag = 1
while i <= t:
if word[i].isalpha() == False and word[i] != '-':
flag = 0
break
i += 1
if word_len > maxlen and flag == 1:
maxlen = word_len
longest = word
maxf = f
maxt = t
# print(longest,maxf,maxt)
print(longest[maxf:maxt+1].lower())
C++版本AC代码
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
//#define ZANGFONG
char longest[110],word[110];
char END[] = "E-N-D";
int main()
{
#ifdef ZANGFONG
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif // ZANGFONG
int f,t,i,len,len1;
int maxf,maxt,maxlen = 0;
while(scanf("%s",word))
{
if(strcmp(END,word)==0) break;
len1 = strlen(word);
len = len1;
i = 0;
while(i < len && isalpha(word[i])== false && word[i] != '-')
{
i++;
len1--;
}
f = i;
i = len-1;
while(i >=0 && isalpha(word[i])== false && word[i] != '-')
{
i--;
len1--;
}
t = i;
int flag = 1;
for(i = f; i <= t; i++)
if(isalpha(word[i]) == false && word[i] != '-'){flag = 0; break;}
if(len1 > maxlen && flag)
{
maxlen = len1;
strcpy(longest,word);
maxf = f;
maxt = t;
}
}
len = 0;
for(i = maxf; i <= maxt; i++)
putchar(tolower(longest[i]));
printf("\n");
return 0;
}