这种寻找最长公共子串解决方案的方法是否属于动态编程?

时间:2017-07-17 23:52:11

标签: java dynamic-programming

我已经开始学习动态编程,这样我编写了一个程序来查找和编写两个给定字符串的最长公共子字符串并且它正在执行正常,之后我继续google并搜索相同的,但是每个人都使用矩阵或(双维数组)来存储子问题解决方案。但我只使用单一尺寸,我相信,我的解决方案的时间复杂度是O(n * m)。我只是想确认我的解决方案是否真的是动态编程。

import java.lang.reflect.Array;
 import java.util.Arrays;
 import java.util.ArrayList;
 public class LongestCommonSubstring {
    private class LCSUtility {
        int lengthOfLCS;
        ArrayList<String> lcsList;
        LCSUtility() {
            lcsList = new ArrayList<>();
            lengthOfLCS=0;
        }
    }
    public LCSUtility findLongestCommonSubstring(String str1,String str2) {
      int[] lcs = new int[str1.length()];
      LCSUtility lcsUtility= new LCSUtility();
      /* Filling out the 1-D array with 1 if that character from "first string is existed in "second string" otherwise 0"*/  
      for(int i=0;i<str1.length();i++){
          if(str2.contains(str1.substring(i,i))) {
              lcs[i] =1;
          } else {
              lcs[i] =0;
          }
        }
        /* Finding the sub strings of "first string" are part of "second string" and storing results into 1-D array*/
        for(int i=1;i<str1.length();i++){
            String sub = str1.substring(i-1,i+1);
            if(str2.contains(sub)) {
                lcs[i] = 1+lcs[i-1];
            }
        }
        /* Finding Max of the LCSs*/
        for(int i=0;i<lcs.length;i++){
            System.out.print(" " + lcs[i]);
            if(lcs[i]>lcsUtility.lengthOfLCS) {
                lcsUtility.lengthOfLCS=lcs[i];
            }
        }
        /* Adding out all lcs to the utility object's list*/
        for(int i=0;i<lcs.length;i++) {
            if(lcs[i] == lcsUtility.lengthOfLCS) {
                lcsUtility.lcsList.add(str1.substring(i-lcsUtility.lengthOfLCS+1,i+1));
            }
        }
        return lcsUtility;
    }


    public static void main(String[] args){
        LCSUtility lcsUtility = new LongestCommonSubstring().findLongestCommonSubstring("tutorialhorizon", "dynamictutorialProgramming hellow");
        System.out.print(" ******* Longest Common Sub of Given Strings are  \n");
        for(String s: lcsUtility.lcsList) {
            System.out.print(" " +s);
        }
    }
}

0 个答案:

没有答案