Java练习(获取两个字符串中最⼤相同⼦串)package ;
import org.junit.Test;
import java.util.Arrays;
public class StringDemo2 {
/*
获取两个字符串中最⼤相同⼦串,⽐如:
str1 = "abcwerthelloyuiodef" ; str2 = "cvhellobnm"
提⽰:将短的那个串进⾏长度依次递减的⼦串与较长的串⽐较。
*/
public String getMaxSameString(String str1, String str2){
String maxStr = (str1.length() >= str2.length())? str1 : str2;
String minStr = (str1.length() <  str2.length())? str1 : str2;
int length = minStr.length();
for (int i = 0; i < length; i++){
for (int x = 0, y = length - i; y <= length; x++, y++){
String subStr = minStr.substring(x, y);
if (ains(subStr)){
return subStr;
}
}
}
return null;
}
// 如果存在多个长度相同的最⼤相同⼦串
// 此时先返回 String[], 后⾯可以⽤集合中的 ArrayList 替换,较⽅便
public String[] getMaxSameString1(String str1, String str2){
if (str1 != null && str2 != null){
StringBuffer sBuffer = new StringBuffer();
String maxString = (str1.length() > str2.length()) ? str1 : str2;
String minString = (str1.length() > str2.length()) ? str2 : str1;
int len = minString.length();
for (int i = 0; i < len; i++){
for (int x = 0, y = len - i; y <= len; x++, y++){
String subString = minString.substring(x, y);
if (ains(subString)){
sBuffer.append(subString + ",");
}
}
//                System.out.println(sBuffer);
if (sBuffer.length() != 0){
break;
}
}
String[] split = String().replaceAll(",$", "").split("\\,");
return split;
}
return null;
}
字符串长度最大是多少@Test
public void testGetMaxSameString(){
String str1 = "abcwerthelloyuiodef";
String str2 = "cvhellobnm";
String[] maxSameStrings = getMaxSameString1(str1, str2);
System.out.String(maxSameStrings));
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。