0
点赞
收藏
分享

微信扫一扫

笔试算法《最长公共子串》


描述
查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。
注:子串的定义:将一个字符串删去前缀和后缀(也可以不删)形成的字符串。请和“子序列”的概念分开!

本题含有多组输入数据!
输入描述:
输入两个字符串

输出描述:
返回重复出现的字符
示例1
输入
abcdefghijklmnop
abcsafjklmnopqrstuvw

输出:
jklmnop

代码

public class Huawei最长公共子串 {

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String a = null;
while ((a = br.readLine()) != null) {
String b = br.readLine();
if(a.length()<b.length()){
System.out.println(maxLengthStr(a.toCharArray(),b.toCharArray()));
}else{
System.out.println(maxLengthStr(b.toCharArray(),a.toCharArray()));
}
}

}

public static String maxLengthStr(char[] a, char[] b) {
int start = 0;
int max = 0;
int[][] ins = new int[a.length + 1][b.length + 1];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
ins[i + 1][j + 1] = ins[i][j] + 1;
if (ins[i + 1][j + 1] > max) {
max = ins[i + 1][j + 1];
start = i - max;
}
}
}
}
return String.valueOf(a).substring(start+1,start+1+max);
}
}

算法逻辑图

笔试算法《最长公共子串》_字符串


举报

相关推荐

0 条评论