Obtains all the common substrings of two strings.
Application Scenario: obtain all the common substrings of two strings.
Idea: 1. first obtain the intersection of two substrings
2. traverse the intersection substring from the shortest substring to the oldest substring
public static List
getAllCommonSubStrings(String str1, String str2) { //TODO null check. String longString = str1; String shortString = str2; if(str1.length() < str2.length()){ longString = str2; shortString = str1; } List
result = new ArrayList
(); List
vacancy = new ArrayList
(); vacancy.add(); List
list1 = Arrays.asList(shortString.split()); List
list2 = Arrays.asList(longString.split()); result.addAll(list1); result.retainAll(list2); result.removeAll(vacancy); List
commonSubStrings = new ArrayList
(); StringBuffer strBuf = new StringBuffer(); for(int i = 0; i < result.size()-1; i++){ strBuf = strBuf.append(result.get(i)); if(shortString.contains(strBuf + result.get(i+1)) && longString.contains(strBuf + result.get(i+1)) && i < result.size()-2){ continue; }else{ commonSubStrings.add(strBuf.toString()); strBuf = new StringBuffer(); } } String tail = commonSubStrings.get(commonSubStrings.size()-1)+ result.get(result.size()-1); if(shortString.contains(tail) && longString.contains(tail)){ commonSubStrings.set(commonSubStrings.size()-1, tail); }else{ commonSubStrings.add(result.get(result.size()-1)); } return commonSubStrings; }