日期:2014-05-20  浏览次数:20723 次

JAVA最大字符子串问题!
str1= "abecderghjk "
str2= "hjkdfhjkjieg "
str3= "iwouuemdfmkhjsgbbxvamnnhs "
str4= "jsahbbbaaxxx "
str5= "ynsghasbavxc "
用一JAVA程序比较出5字符串中最长的公共子串。(不可以求出所有公共子串后再比较长度,得出最长子串)

------解决方案--------------------
没啥好主意,写了个没啥技术含量的:
import java.util.*;
public class TR{
public static void main(String[] args){
String str1= "abec8947dergah8jk ";
String str2= "hjkdfhjkah8jieg894 ";
String str3= "28942iwouuemah8dfmkhjsgbbxvamnnhs ";
String str4= "jsahbbbaaxxah8x025894 ";
String str5= "ah8ns894ghasbavxc ";
ArrayList results = new ArrayList();
int maxLength = 0;
for(int start=0; start <str1.length(); start++){
String s = " ";
for(int end=start+1; end <str1.length(); end++){
String temp = str1.substring(start, end);
if(str2.indexOf(temp)==-1) break;
if(str3.indexOf(temp)==-1) break;
if(str4.indexOf(temp)==-1) break;
if(str5.indexOf(temp)==-1) break;
s = temp;
}
if(s.length() == 0){
continue;
}
if(s.length() > maxLength){
results.clear();
results.add(s);
maxLength = s.length();
}else if(s.length() == maxLength){
results.add(s);
}
}
for(int i=0; i <results.size(); i++){
System.out.println((String)results.get(i));
}
}
}