The Japanese language is notorious for its sentence ending particles. Personal preference of such particles can be considered as a reflection of the speaker's personality. Such a preference is called "Kuchiguse" and is often exaggerated artistically in Anime and Manga. For example, the artificial sentence ending particle "nyan~" is often used as a stereotype for characters with a cat-like personality:
Itai nyan~ (It hurts, nyan~)
Ninjin wa iyada nyan~ (I hate carrots, nyan~)
Now given a few lines spoken by the same character, can you find her Kuchiguse?
Input Specification:
Each input file contains one test case. For each case, the first line is an integer N (2≤N≤100). Following are N file lines of 0~256 (inclusive) characters in length, each representing a character's spoken line. The spoken lines are case sensitive.
Output Specification:
For each test case, print in one line the kuchiguse of the character, i.e., the longest common suffix of all N lines. If there is no such suffix, write
nai
.Sample Input 1:
3 Itai nyan~ Ninjin wa iyadanyan~ uhhh nyan~
Sample Output 1:
nyan~
Sample Input 2:
3 Itai! Ninjinnwaiyada T_T T_T
Sample Output 2:
nai
作者: HOU, Qiming
单位: 浙江大学
时间限制: 150 ms
内存限制: 64 MB
代码长度限制: 16 KB
重点:过滤输入n后的换行符!
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <set>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
getchar();//重要!!!否则就不对!
string res;//res得到公共最长后缀
for(int i = 0 ; i < n;i++)
{
string str;
getline(cin,str);
int len = str.length();
reverse(str.begin(),str.end());//翻转字符串,从最后一个开始比较
if(i == 0)
{
res = str;//先把公共最长后缀默认为第一条输入的字符串
continue;
}
else
{
int lenres = res.length();
int minlen = min(lenres,len);
for(int j = 0;j < minlen;j++)
{
if(res[j] != str[j])
{
res = res.substr(0,j);//到第j个不相等了,最长公共部分就是之前匹配的,截取下来
break;
}
}
}
}
reverse(res.begin(),res.end());//翻转输出
if(res.length() == 0)
res = "nai";
cout<<res;
return 0;
}