题目:
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
解题思路:我是想建立一个字符串数组,逆序后一个一个地比对,的出来的答案放在一个res字符串数组中,取最短的那个作为最终结果,然后再逆序输出。但是逻辑有哪里怪怪的....虽然还是全过了,但是我做了n久....
代码:
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
using namespace std;
int main(){
set<string> st;
int n;
//freopen("input.txt","r",stdin);
cin>>n;
string res[n+1],s[n+1];
//int i=0;
getchar();//很重要!!用于吸收空格!
for(int i=0;i<n;i++){
getline(cin,s[i]);
//cout<<s[i]<<endl;
}
for(int i=0;i<n;i++){
reverse(s[i].begin(),s[i].end());
}
bool flag=true;
for(int j=0;j<n;j++){
for(int k=0;k<s[j].length();k++){
if(s[j][k]==s[j+1][k]){
//if(s[j].find(s[j+1][k])!=string::npos){
//if(res.find(s[j+1][k])!=string::npos)continue;
//else res+=s[j+1][k];
res[j]+=s[j+1][k];
flag=true;
}
else break;
}
}
int t=0;
int minlen=res[0].length();
for(int i=1;i<n-1;i++){
if(res[i].length()<minlen){
minlen=res[i].length();
t=i;
}
}
//cout<<res[t];
reverse(res[t].begin(),res[t].end());
if(res[t]!="")cout<<res[t];
else cout<<"nai";
return 0;
}
这种时候就不如直接膜柳神了:(柳神好强啊!发出膜拜的声音)
解题思路:因为是后缀,反过来比较太麻烦,所以每输入一个字符串,就把它逆序过来再比较会比较容易~
首先ans = s;后来每输入的一个字符串,都和ans比较,如果后面不相同的就把它截取掉,最后输出ans即可(要逆序输出~,所以先将ans倒置reverse一下~)
https://www.liuchuo.net/archives/2065
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
scanf("%d\n", &n);
string ans;
for(int i = 0; i < n; i++) {
string s;
getline(cin, s);
int lens = s.length();
reverse(s.begin(), s.end());
if(i == 0) {
ans = s;
continue;
} else {
int lenans = ans.length();
if(lens < lenans) swap(ans, s);
int minlen = min(lens, lenans);
for(int j = 0; j < minlen; j++) {
if(ans[j] != s[j]) {
ans = ans.substr(0, j);
break;
}
}
}
}
reverse(ans.begin(), ans.end());
if (ans.length() == 0) ans = "nai";
cout << ans;
return 0;
}