黑马程序员技术交流社区
标题:
找出两个字符串的最大公共子串
[打印本页]
作者:
Evangelvii
时间:
2012-4-24 16:15
标题:
找出两个字符串的最大公共子串
找出两个字符串的最大公共子串,比如说s1="asdeferdere",s2="cvvsdefrrt"两者的最大公共子串为"sdef"
import java.util.LinkedList;
import java.util.List;
public class Clothes {
public static void main(String[] args) {
String s2 = "45aefg1234";
String s1 = "12345aesadaefgfewfw";
zdggzc(s2, s1);
}
static void zdggzc(String s1, String s2) {
String temp;
if (s1.length() < s2.length()) {
temp = s1;
s1 = s2;
s2 = temp;
temp = null;
}
List<String> zdggzc = new LinkedList<String>();
int result = 0;
StringBuilder maxSubStr = new StringBuilder();
for (int i = 0; i <= s1.length() - 1; i++) {
char curChar = s1.charAt(i);
int indexInS2 = 0;
boolean flag = false;
while (true) {
if (flag) {
break;
}
if (indexInS2 > s2.length() - 1) {
break;
}
indexInS2 = s2.indexOf(curChar, indexInS2);
if (indexInS2 == -1) {
break;
}
maxSubStr.append(curChar);
int offInS1 = i;
int offInS2 = indexInS2;
while (true) {
offInS1++;
offInS2++;
if (offInS1 > s1.length() - 1 || offInS2 > s2.length() - 1) {
flag = true;
break;
}
if (s1.charAt(offInS1) == s2.charAt(offInS2)) {
maxSubStr.append(s1.charAt(offInS1));
} else {
indexInS2++;
break;
}
}
if (maxSubStr.length() >= result) {
result = maxSubStr.length();
zdggzc.add(maxSubStr.toString());
}
maxSubStr.delete(0, maxSubStr.length());
}
}
for (String string : zdggzc) {
System.out.println(string);
}
}
}
复制代码
有没有简单的方法
作者:
孙天
时间:
2012-4-24 17:58
1。将长度较短作为参照,对其进行取子串,并将其子串在另一个字符串中进行匹配。
从大往小取,长度依次递减。
*/
public String getMaxString(String str1,String str2)
{
String max="";
for(int x=0;x<str2.length();x++)
{
String temp1=str2.substring(x);
for(int y=temp1.length();y>0;y--)
{
String temp2=temp1.substring(0,y);
if((str1.indexOf(temp1))!=-1&&temp2.length()>max.length())
max=temp2;
}
}
return max;
}
/*
第二种方式。获取长度最大的子串,进行匹配,不满足,长度依次递次递增减减
将每一次长度递减的子串全部取出进行匹配。
*/
public String getMaxString_2(String str1,String str2)
{
for(int x=0;x<str2.length();x++)
{
for(int y=0,z=str2.length()-x;z<=str2.length();y++,z++)
{
String temp=str2.substring(y,z);
if(str1.contains(temp))
return temp;
//System.out.println(temp);
}
}
return "";
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2