码迷,mamicode.com
首页 > 编程语言 > 详细

获取两个字符串全部公共的子串算法

时间:2016-03-01 12:51:34      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

应用场景: 获取两个字符串全部公共的子串。

思路: 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!