A1077 Kuchiguse (20分)
一、题目描述
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:
1.Itai nyan~ (It hurts, nyan~)
2.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
二、题目大意
给定N个字符串,找出这N个字符串的公共后缀,若存在,则输出该公共后缀,若不存在,则输出nai。
三、思路
①:首先是输入, cin 或者scanf()函数会留下一个换行符,需要使用getchar()把换行符给读取掉,否则get或者getline函数会把这个换行符读入,导致第一个字符串读取错误。
②:考虑到公共后缀需要从后往前枚举字符串,因此不妨把字符串给反转过来,这样就会把问题转换为求N个字符串的公共前缀,这样思考会简单更多。
③:为了防止字符串越界,还需要事先找到这N个字符串的最小长度minlen。这可以在读入的时候计算出。
④:找出最小长度后,我们就可以枚举N个字符串中的[0,minlen)中的所有字符,判断相同位置的字符是否相同,若相同,则进行累加。若不同则结束循环。
四、AC代码
#include<bits/stdc++.h>
using namespace std;
int ans;
int main()
{
int n,minlen = 300;
string str[105];
cin >> n;
getchar();
for(int i = 0 ; i < n ; i ++){
getline(cin,str[i]);
int len = str[i].size();
if(minlen > len ) minlen = len;
for(int j = 0 ; j < len / 2; j ++){
swap(str[i][j],str[i][len - j - 1]);
}
}
for(int i = 0 ; i < minlen ; i ++){
char c = str[0][i];
int flag = 1;
for(int j = 1 ; j < n ; j ++){
if(c != str[j][i]){
flag = 0;
break;
}
}
if(flag) ans++;
else break;
}
if(ans)
for(int i = ans - 1 ; i >= 0 ; i --){
cout << str[0][i];
}
else{
cout << "nai";
}
return 0;
}