779. 最长公共字符串后缀
给出若干个字符串,输出这些字符串的最长公共后缀。
输入格式
由若干组输入组成。
每组输入的第一行是一个整数 NN。
NN 为 00 时表示输入结束,否则后面会继续有 NN 行输入,每行是一个字符串(字符串内不含空白符)。
每个字符串的长度不超过 200200。
输出格式
共一行,为 NN 个字符串的最长公共后缀(可能为空)。
数据范围
1≤N≤2001≤N≤200
输入样例:
3
baba
aba
cba
2
aa
cc
2
aa
a
0
输出样例:
ba
a
题解:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n;
while ((n=Integer.parseInt(bf.readLine()))!=0) {
int max = 201;
String s = bf.readLine();
for (int i = 1; i < n ; i ++){
int res = 0 ;
String a= bf.readLine();
for (int j = 0; j < a.length() && j < s.length(); j++) {
if (a.charAt(a.length() - 1 - j) == s.charAt(s.length() - 1 -j))
res ++;
else break;
}
max = Math.min(max,res);
}
bw.write(s.substring(s.length()-max)+"\n");
}
bw.close();
}
}
评论区