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
题目大意:
日本动漫里人物经常会有口癖,也就是这里的Kuchiguse,同一个人的说话往往每句话结尾都有相同的后缀(就像鸣人的的打跌吧哟)。
现在给你同一个人说的n句话,让你返回相同的后缀,如果没有就返回 nai
,也就是日语的没有的意思
方法一:字符串
思路:
前缀肯定比后缀方便,反转一下后缀就能变成前缀,
随后从第一句话的第一个字符开始,往后判断是否相同,遇到不同的就跳出循环
C++ 代码:
// pat_a_1077
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n, len = 0x3f3f3f3f;
string s[110], ans;
int main(){
cin >> n;
cin.get(); // 为了清空读入n后残余的换行符
for(int i = 0; i < n; i++ ){
getline(cin, s[i]);
reverse(s[i].begin(), s[i].end()); // 反转为了方便
len = min(len, int(s[i].length()));
}
for(int i = 0; i < len; i++ ){
bool flag = 1; // 当前位是否相同 1相同 0不同
// 判断第i位
char cur = s[0][i];
for(int j = 1; j < n; j++ ){
if(s[j][i] != cur){
flag = 0;
break;
}
}
if(flag)
ans += cur;
else
break;
}
if(ans.size() == 0)
cout << "nai" << endl;
else{
reverse(ans.begin(), ans.end());
cout << ans << endl;;
}
return 0;
}
复杂度分析:
- 时间复杂度:O(n),最多遍历到最后一句话的最后一个字符
- 空间复杂度:O(n),每句话都会存下来