题目来源:PAT (Advanced Level) Practi
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
words:
notorious 臭名昭著的,身名狼藉的 particle 颗粒,粒子 reflection 反映,反射
personality 性格,个性 artistically 艺术地 ,美术地 Anime 动漫 Manga 漫画
stereotype 刻板印象 exaggerated 夸张的,夸大的 suffix 后缀 prefix 前缀
思路:
1. 本题的意思是根据给出的n个字符串,找出它们的共同的后缀并输出,若没有则输出“nai”;
2. 使用字符串数组s[n]保存n个字符串,为了便于后缀的比较,数组中保存字符串的反序字符串;
3.从第0个字符开始,逐一对比每个字符串中的字符是否相同,若都相同则将该字符保存到字符串ans中以备输出并且对比下一个字符,否则停止对比;
4.若n个字符串的没有相同的后缀,即字符串ans为空,则输出“nai”,否则输出ans;
5. reverse(s.begin(),s.end()) 用于将字符串s反序过来,如将 “abc” 转换为 “cba” ;
6. cin.ignore() 用于忽略 cin>>n 后边的换行符;
//PAT ad 1077 Kuchiguse
#include <iostream>
using namespace std;
#include <algorithm>
#include <set>
bool test_k(int k,int *a,int n) //判断k是否小于数组a中的每一个数
{
for(int i=0;i<n;i++)
if(k>=a[i])
return false;
return true;
}
int main()
{
int n,i;
cin>>n;
string s[n];
int len[n];
cin.ignore(); //忽略 cin>>n 后边的换行符
for(i=0;i<n;i++)
{
getline(cin,s[i]); //字符串输出(含有空格)
len[i]=s[i].size();
reverse(s[i].begin(),s[i].end()); //字符串反序
}
int k=0;
string ans;
while(test_k(k,len,n))
{
set<char> se;
for(i=0;i<n;i++)
se.insert(s[i][k]);
if(se.size()==1)
ans=s[0][k]+ans;
else
break;
k++;
}
if(ans.empty())
ans="nai";
cout<<ans<<endl;
return 0;
}