题目来源
注意点:
- 有部分输入的细节,见后文
Description
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 ) N (2≤N≤100) N(2≤N≤100). Following are N N N file lines of 0 256 0~256 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 N 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
题目大意
给出若干字符串,输出它们的最长公共后缀
思路简介
最长公共后缀
用第一个字符串与后续的字符串从后往前以一比对即可
python 的 os 库提供字符串公共前缀函数用于文件处理,可以把字符串倒转后求公共前缀来解题
遇到的问题
c++版
- 从末尾开始比对字符时,注意记录的是匹配失败的位置,要加 1 1 1 才是匹配成功的位置
代码
cpp
/**
* https://www.nowcoder.com/pat/5/problem/4307
* https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805390896644096
* 最长后缀匹配
*/
#include<bits/stdc++.h>
using namespace std;
string s[200];
void solve(){
int n;
cin>>n;
cin.ignore();//避免读取换行
for(int i=0;i<n;++i)
getline(cin,s[i]);
int p=0;
for(int i=1;i<n;++i){
int k1=s[0].size()-1;
int k2=s[i].size()-1;
while(k1>=0&&k2>=0&&s[i][k2]==s[0][k1])
k1--,k2--;
p=max(p,k1+1);//注意k1是对比后减去1的位置,加回1才是配对的位置
}
if(p==s[0].size())cout<<"nai\n";
else {
cout<<s[0].substr(p)<<'\n';
}
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//fstream in("in.txt",ios::in);cin.rdbuf(in.rdbuf());
int T=1;
//cin>>T;
while(T--){
solve();
}
return 0;
}
python
import os
def common_suffix(strs):#输入字符串列表
strs_reverse=[s[::-1] for s in strs]#构造反转字符串的列表
res=os.path.commonprefix(strs_reverse)#获取文件路径公共前缀
if(res):return res[::-1]
else: return "nai"
import sys
def main():
#sys.stdin = open('in.txt') # 本地测试用,提交时注释掉
n = int(input()) # 读取整数
lines = [input() for _ in range(n)] # 读取 n 行字符串(可含空格)
res=common_suffix(lines)
print(res)
if __name__=="__main__":
main()