您的位置:首页 > 其它

求两个字符串的最长公共子串

2018-02-27 22:04 232 查看
要求:求两个字符串的最长公共子串,如“abcdefg”和“adefgwgeweg”的最长公共子串为“defg”(子串必须是连续的)package com.nowcoder.wenda.agrithom;

/**
* Created by wuyunlong on 18-2-27.
*/
public class MaxSubString {

public static String maxSubstring(String strOne,String strTwo){

if (strOne == null || strTwo == null){
return null;
}
if (strOne.equals("")|| strTwo.equals("")){
return null;
}
String max = "";
String min = "";
if(strOne.length()<strTwo.length()){
min = strOne;
max = strTwo;
}else{
min = strTwo;
max = strOne;
}
String current = "";
for(int i=0; i<min.length(); i++){
//每次都把begin置位0,end置位min.length()-i,然后同时往后移动
for(int begin=0, end=min.length()-i; end<=min.length(); begin++){
current = min.substring(begin, end);
if(max.contains(current)){
return current;
}
end++;
}
}
return "";
}

public static String maxSubstring1(String strOne,String strTwo){
if(strOne == null || strTwo == null){
return null;
}
if(strOne.equals("")||strTwo.equals("")){
return null;
}
int len1 = strOne.length();
int len2 = strTwo.length();
// 保存矩阵的上一行
int[] topLine = new int[len1];
//保存矩阵当前行
int[] currentLine = new int[len1];

// 矩阵元素中的最大值
int maxLen = 0;
// 矩阵元素最大值出现在第几列
int pos = 0;
char ch = ' ';
for(int i=0; i<len2; i++){
ch = strTwo.charAt(i);
// 遍历str1,填充当前行的数组
for(int j=0; j<len1; j++){
if( ch == strOne.charAt(j)){
// 如果当前处理的是矩阵的第一列,单独处理,因为其坐上角的元素不存在
if(j==0){
currentLine[j] = 1;
} else{
currentLine[j] = topLine[j-1] + 1;
}
if(currentLine[j] > maxLen){
maxLen = currentLine[j];
pos = j;
}
}
}
// 将矩阵的当前行元素赋值给topLine数组; 并清空currentLine数组
for(int k=0; k<len1; k++){
topLine[k] = currentLine[k];
currentLine[k] = 0;
}

}
return strOne.substring(pos-maxLen+1, pos+1);
}
public static void main(String[] args) {
String strOne = "babssss";
String strTwo = "caba";
// String result = MaxSubString.maxSubstring(strOne, strTwo);
String result = MaxSubString.maxSubstring1(strOne,strTwo);
System.out.println(result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: