多个字符串的公共最长连续子串(对两个字符串的扩展)
来源:互联网 发布:oracle sql 重复数据 编辑:程序博客网 时间:2024/05/01 21:07
求两个字符串的最长连续公共子串用动态规划,参考http://blog.csdn.net/shandianling/article/details/7913818。存储空间是一个二维数组。
对于多个字符串也可用这个办法,求的是广义的对角线,存储空间是一个多维数组。
代码如下
import java.util.HashMap;import java.util.Map;public class Solution {public static void main(String[] args){System.out.println( new Solution().commonStrLen(new String[]{"abcdefg","abcde","cdef","defg"} ) );}//preKey是key的对角线public String commonStrLen(String[] strArray){String result;//公共子串的长度和strArray的结束为止int maxLength = 0;int endIndex = 0;//相当于是存放多维的矩阵,当值为0时不用存储,节省空间Map<String,Integer> multiArray = new HashMap<String,Integer>();int size = strArray.length;int totalSize = 1;//index代表strArray各元素的当前下标int[] index = new int[size];for(int i=0;i<size;i++){index[i] = 0;totalSize *= strArray[i].length();}int k = 0;if(totalSize==0)return "";else{while(k<totalSize){//得到字符char now = strArray[0].charAt(index[0]);boolean isEqual = true;for(int i=0;i<size;i++){if(now!=strArray[i].charAt(index[i]))isEqual = false;}//全部相等后if( isEqual ){String preKey = "";String key = "";for(int i=0;i<size;i++){preKey += index[i]-1;key += index[i];}if(multiArray.get(preKey)!=null){multiArray.put(key, multiArray.get(preKey)+1);if(maxLength<multiArray.get(preKey)+1){maxLength = multiArray.get(preKey)+1;endIndex = index[0];}}else{multiArray.put(key, 1);if(maxLength<1){maxLength = 1;endIndex = index[0];}}}//注意下标的增长方式index[size-1] +=1;for(int i=size-1;i!=-1;i--){if(index[i]==strArray[i].length()){index[i] = 0;if(k!=totalSize-1)index[i-1] +=1;}}k++;}result = strArray[0].substring( endIndex+1-maxLength , endIndex+1 );return result;}}}
时间复杂度为O(N1*N2*...),其中Ni表示第i个数组的长度。
还在探寻更好的算法。。。 0 0
- 多个字符串的公共最长连续子串(对两个字符串的扩展)
- 字符串操作:两个字符串的最长连续公共子串
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长连续公共子串
- 两个字符串的最长连续公共子串
- 求两个字符串的最长公共子串(包括连续和非连续)
- 两个字符串的第一个最长公共子串
- 两个字符串的最长公共子序列(可以不连续)
- 求两个字符串的最长的连续公共子串和求两个字符串的公共子序列
- 求两个字符串的最长的连续公共子串(按位异或法)
- 求两个字符串的(连续的)最长公共子串
- 两个字符串的最长公共子串
- 两个字符串的最长公共子串
- 两个字符串的最长公共子串
- 两个字符串的最长公共子串
- 平衡二叉排序树
- Remoting原理及实现
- 财务常用计算公式
- android expendableListView教程
- leetcode||Pascal's Triangle II
- 多个字符串的公共最长连续子串(对两个字符串的扩展)
- linux 下部署多个tomcat
- 关于request,session,application
- 工作中eclipse崩溃,状态栏一直显示Initializing Java Tooling: (30%)
- 用MFC画椭圆
- STM32串口发送
- synchronizedList与会抛出ConcurrentModificationException
- 2014 Gartner IaaS魔力象限市场报告解读
- Apache的Order Allow,Deny 详解