给出两个字符串,求出其最大的相同子串。
package stringtest; /** * 思路:截取最小串(截取的时候先截取最大长度,然后依次减一),去匹配大串。 */ import java.util.ArrayList; import java.util.List; public class MaxSubString { public static void main(String[] args) { String s1 = "afea"; String s2 = "afebcd"; System.out.println(maxSubString(s1, s2)); } //求str2在str1中最大的相同子串 public static List<String> maxSubString(String str1,String str2) { String maxString = (str1.length() >= str2.length()) ? str1 : str2; String minString = (str1.length() >= str2.length()) ? str2 : str1; List<String> listSring = new ArrayList<String>(); for (int i = 0; i < minString.length(); i++) { for (int x = 0 , y = minString.length() - i -1; y < minString.length(); x++ , y++) { //substring是左闭右开的 if (maxString.contains(minString.substring(x, y+1))) { listSring.add(minString.substring(x, y+1)); } } if (!listSring.isEmpty()) { return listSring; } } return listSring; } }