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

获取两个字符串所有公共的子串算法

时间:2015-07-01 18:12:35      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:string   util   算法   常用算法   

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

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


版权声明:本文为博主原创文章,未经博主允许不得转载。

获取两个字符串所有公共的子串算法

标签:string   util   算法   常用算法   

原文地址:http://blog.csdn.net/chndata/article/details/46712669

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