题目描述
The Japanese language is notorious for its sentence endingparticles. Personal preference of such particles can be considered as areflection 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 oftenused 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?
输入描述:
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) charactersin length, each representing a character's spoken line. The spoken lines arecase sensitive.
输出描述:
For each test case, print in one line the kuchiguse of thecharacter, i.e., the longest common suffix of all N lines. If there is no suchsuffix, write "nai".
输入例子:
3
Itai nyan~
Ninjin wa iyadanyan~
uhhh nyan~
输出例子:
nyan~
这一题其实就是找所有的字符串的公共最长后缀,
从所有的字符串后面往前搜索,直到直到第一个不相同的字母为止,找到的子串就是所有的字符串的最长公共子串
我开始以为这里的子串不能包括空格,但是这一题实际上是让你找公共子串,这里的公共子串是能够包含空格的,题目没有给你的条件不要自己去猜
还有一点需要注意就是题目中给的子串是带空格的,当对string输入带空格的字符串的时候需要使用getline(cin.string),前面还需要使用cin.get()去除前面的空格,以后在做题的时候需要注意一下
#include <iostream>
#include <string>
using namespace std;
string thenum[103];
int main()
{
int N;
int i,j;
int theMinL;
char theTmp;
cin>>N;
cin.get();
for(int i=0;i<N;i++)
{
getline(cin,thenum[i]);
theMinL = thenum[i].size();
}
for(i=1;i<=theMinL;i++)
{
theTmp=thenum[0][thenum[0].size()-i];
for(j=1;j<N;j++)
{
if(thenum[j][thenum[j].size()-i]==theTmp) continue;
else break;
}
if(j==N)
{
}
else{
if(i==1)
{
cout<<"nai"; break;
}
else
{
cout<<thenum[0].substr(thenum[0].size()-(i-1),i-1);
break;
}
}
}
if(i>theMinL)
cout<<thenum[0];
return 0;
}