Java 这种寻找最长公共子串解的方法是否属于动态规划?
我已经开始学习动态规划,通过这种方式,我编写了一个程序来查找和编写两个给定字符串的最长公共子字符串,它执行得很好,之后我转到谷歌搜索相同的字符串,但每个人都使用矩阵或(双维数组)来存储子问题的解决方案。但我只使用了一维,我相信,我的解决方案的时间复杂度是O(n*m)。我只是想确认我的解决方案是否真的是动态规划Java 这种寻找最长公共子串解的方法是否属于动态规划?,java,dynamic-programming,Java,Dynamic Programming,我已经开始学习动态规划,通过这种方式,我编写了一个程序来查找和编写两个给定字符串的最长公共子字符串,它执行得很好,之后我转到谷歌搜索相同的字符串,但每个人都使用矩阵或(双维数组)来存储子问题的解决方案。但我只使用了一维,我相信,我的解决方案的时间复杂度是O(n*m)。我只是想确认我的解决方案是否真的是动态规划 import java.lang.reflect.Array; import java.util.Arrays; import java.util.ArrayList; public
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);
}
}
}
import java.lang.reflect.Array;
导入java.util.array;
导入java.util.ArrayList;
公共类最长公共子字符串{
私有类可访问性{
国际长途航班;
ArrayList-lcsList;
立法会(修订){
lcsList=newarraylist();
长度=0;
}
}
public lcsutibility findLongestCommonSubstring(字符串str1、字符串str2){
int[]lcs=newint[str1.length()];
lcsutibility lcsutibility=新的lcsutibility();
/*如果“第一个字符串”中的字符存在于“第二个字符串”中,则用1填充一维数组,否则为0“*/
对于(int i=0;我的问题可能更适合Hi@Chris谢谢你的建议,我会尝试一下。这个问题可能更适合Hi@Chris谢谢你的建议,我会尝试一下。