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
Ω
寻找最长公共后缀,无则输出“nai”。
最简单的想法就是先把所有句子存到一个vector里,然后一起从后往前数。
事实上不需要这么麻烦,只要每次读入一个新句子后和当前公共后缀从后至前进行比较,然后存取新的公共后缀。当然嫌从后往前麻烦,就把他们都reverse一下。
⚠️使用getline时注意上一行是否读完,包括’\n’(需要getchar一下)。
🐎
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, k;
cin >> n;
string ans, tmp;
getchar(); //get '\n'
getline(cin, ans);
reverse(ans.begin(), ans.end());
for (int i = 1; i < n; ++i)
{
getline(cin, tmp);
reverse(tmp.begin(), tmp.end());
for (k = 0; k < min(ans.size(), tmp.size()); ++k)
if (ans[k] != tmp[k])
break;
ans = ans.substr(0, k);
}
reverse(ans.begin(), ans.end());
cout << (ans.empty() ? "nai" : ans);
}