应用场景: 获取两个字符串所有公共的子串。
思路: 1. 先获取两个子串的交集
2. 遍历交集子串,从最短子串到最长子串
public static List<String> getAllCommonSubStrings(String str1, String str2) { //TODO null check. String longString = str1; String shortString = str2; if(str1.length() < str2.length()){ longString = str2; shortString = str1; } List<String> result = new ArrayList<String>(); List<String> vacancy = new ArrayList<String>(); vacancy.add(""); List<String> list1 = Arrays.asList(shortString.split("")); List<String> list2 = Arrays.asList(longString.split("")); result.addAll(list1); result.retainAll(list2); result.removeAll(vacancy); List<String> commonSubStrings = new ArrayList<String>(); 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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-25 14:05:33