longest common substring ,giving error why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

longest common substring ,giving error why?

import java.util.Arrays; public class Solution { public static int lcs(String str1, String str2){ int dp[][]=new int [str1.length()][str2.length()]; for(int r[]:dp){ Arrays.fill(r, -1); } return helper(0,0,str1,str2,0,dp); } public static int helper(int i,int j,String s1, String s2,int currentlength,int dp[][]){ if(i>=s1.length()||j>=s2.length()) return currentlength; if(dp[i][j]!=-1) return dp[i][j]; int pick=0; if(s1.charAt(i)==s2.charAt(j)) pick= helper(i+1, j+1, s1, s2,currentlength+1,dp); int notpick=Math.max(helper(i+1, j, s1, s2, 0,dp), helper(i, j+1, s1, s2, 0,dp)); dp[i][j]= Math.max(currentlength, Math.max(pick, notpick)); return currentlength=dp[i][j]; } }

29th Sep 2023, 2:46 PM
subrat yadav
2 Answers
+ 2
writing your code in the post makes it difficult for anyone to debug your code/see error(s) it is throwing. Please save your code in the playground and include a link to it in your post. other things to consider when posting for help: -what error(s) are you getting? -what should your code return/display on console? -what kind of input do you need to provide when running the code? -is this from a lesson? if so, what lesson? what is the objective? also, you have two codes in your post, which one are you wanting help with?
29th Sep 2023, 4:31 PM
Aaron Lee
Aaron Lee - avatar
0
I did it Like this : import java.util.*; public class Program { static boolean isSub(String ss, String[] lst) { int c=0; for (String w : lst) if (w.contains(ss)) c += 1; return c == lst.length; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); //String[] ws = "SoloLearn Learning LearningIsFun Learnable".split(" "); String[] ws = sc.nextLine().split(" "); String fw = ws[0]; String lcs = fw.charAt(0) + ""; // String.valueOf(); for (int i=0; i<fw.length(); i++) { for (int j=i+2; j<fw.length()+1; j++) { //System.out.format("%d %c %d %s \n", i, fw.charAt(i), j, fw.substring(i, j) ); if (isSub( fw.substring(i, j), ws) ) if ( fw.substring(i, j).length() > lcs.length() ) lcs = fw.substring(i, j); } } System.out.println (lcs); }
29th Sep 2023, 3:44 PM
D1M3
D1M3 - avatar