題目
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
思路
建立字符串數組,用getline(cin, s[i])
讀取含空格的整行字符串。(注意在這之前要用getchar()喫掉換行符)
以第一個字符串爲基準,從尾到頭檢查所有其它字符串尾部字符是否全部與其相同。若所有尾部都相同則記錄,然後檢查下一個尾部;若不同或有一個字符串到達了頭部則結束。
最後查看記錄的公共字符串,若爲空則輸出“nai”;不爲空則直接輸出。
字符串添加字符時 += 效率更高,因爲不需要重新建立對象,最後倒序輸出即可。
代碼
#include <iostream>
#include <vector>
using namespace std;
int main(){
int n;
cin >> n;
getchar(); //吸收換行符
vector<string> s(n);
for (int i=0; i<n; i++){
getline(cin, s[i]);
}
string common = "";
int j = 1;
while (1){
bool flag = true;
//取s[0]爲基準
if (s[0].size() < j){
break;
}
char ch = s[0][s[0].size()-j];
//檢查剩下的s[1]…s[n-1]
for (int i=0; i<n; i++){
if (s[i].size()<j || s[i][s[i].size()-j]!=ch){
flag = false;
break;
}
}
if (flag){
common += ch;
j++;
}
else{
break;
}
}
if (common.size()==0){
cout << "nai";
}
else{
for (int i=common.size()-1; i>=0; i--){
cout << common[i];
}
}
return 0;
}