/**
获取最大子串
*/
public class MaxSubstring{
public static void main(String[] args){
//长字符串
String s1 = "qwerabcdtyuiop";
//子串
String s2 = "xcabcdtvbn";
//最大子串
String maxSubstring = getMaxSubstring(s1,s2);
//输出内容
String outPut = "最大相同子串是:" + maxSubstring;
//显示输出
System.out.println(outPut);
}
// 获取最大子串
public static String getMaxSubstring(String s1, String s2){
//longString代表长字符串
String longString = null;
//shortString代表短字符串
String shortString = null;
//将参数中长字符赋值给longString
longString = (s1.length() > s2.length())? s1 : s2;
//将参数中短字符串(需查找的子串)赋值给shortString
shortString = (s2.length() < s1.length)? s2 : s1;
//for循环来获取最大子串
for(int x = 0; x < shortString.length(); x++){
for(int i = 0, j = shortString.length()-x; j != shortString.length(); i++, j++){
//声明sub记录截取的子串
String sub = shortString.substring(i,j);
//截取的子串进行判断,返回最大的那个
if(longString.contains(sub))
return sub;
}
}
return null;
}
}
|