PAT 1077 Kuchiguse [一般]

时间:2022-12-06 18:14:48
1077 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:

  • 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

题目大意:给出m个句子,判断所有句子的最长后缀。

//有空格怎么办?那就不是一个character了。。。

#include <iostream>
#include <algorithm>
#include<cstdio>
#include <vector>
#include<cstring>
#include<string.h>
#include<string>
using namespace std; int main()
{
int n;
cin>>n;
string pe="",now;//那就以第一个作为标准,剩下的去和它作比较。
int j=,k=,mins=j;
for(int i=;i<n;i++){//如何读取一行,真的是不会。。。。
getline(cin,now);
if(pe==""){
pe=now;continue;
}
for(j=pe.size()-,k=now.size()-;k>=,j>=;j--,k--){
if(pe[j]!=now[k]){
break;
}
}
if(j<mins){
mins=j;
}
}
if(mins==){
cout<<"nai";
}else{
for(int i=mins;i<pe.size();i++){
cout<<pe[i];
}
} return ;
}

//本来是写成这个样子,根本就不行啊,不过整行读取字符串的函数写的是对的。

根据柳神的修改了之后的,可以AC了

#include <iostream>
#include <algorithm>
#include<cstdio>
#include <vector> using namespace std; int main()
{
int n;
cin>>n;
string pe="",now,ans;//那就以第一个作为标准,剩下的去和它作比较。
getline(cin,now);
for(int i=;i<n;i++){//如何读取一行,真的是不会。。。。
getline(cin,now);
reverse(now.begin(),now.end());
if(i==){
ans=now;
}else{
int j=;
for(j=;j<ans.size()&&j<now.size();j++){
if(ans[j]!=now[j])break;
}
ans=ans.substr(,j);
}
}
reverse(ans.begin(),ans.end());
if(ans=="")
cout<<"nai";
else
cout<<ans;
return ;
}

1.使用reverse进行倒转,因为是比较后缀,不太好比较,最后的答案需要再翻转过来。

2.关于这个getline(cin,now)读取一行的问题,在输入了n之后,其实就有一个\n被getline给读取进来了,所以这样就浪费了一个,需要单独加一个getline来消灭\n才对!

3.使用substr进行截取答案。