获取两个字符串全部公共的子串算法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取两个字符串全部公共的子串算法相关的知识,希望对你有一定的参考价值。
应用场景: 获取两个字符串全部公共的子串。
思路: 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; }
以上是关于获取两个字符串全部公共的子串算法的主要内容,如果未能解决你的问题,请参考以下文章