标签:
应用场景: 获取两个字符串全部公共的子串。
思路: 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; }
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/5230171.html