Word Break Solution using dp memoization
- Manbodh ratre
- Jun 13, 2024
- 1 min read
Problem statement
You are given a list of “N” strings array. Your task is to check whether you can form a given target string using a combination of one or more strings of array.
Note :
You can use any string of array multiple times.
Examples :
array =[“dev”, ”porta”, “is”, “awesome”] target = “devporta”
Ans = true as we use “dev” and “porta” to form “devporta”
import java.util.* ;
import java.io.*;
public class Solution {
public static Boolean wordBreak(String[] arr, int n, String target) {
if(target.isEmpty())
return true;
int[] dp = new int[target.length()+1];
Arrays.fill(dp, -1);
return findAns(Arrays.asList(arr), n, target, dp);
}
public static Boolean findAns(List<String> arr, int n, String target, int[] dp){
if(target.isEmpty()){
dp[0] = 1;
return true;
}
int length = target.length();
if(dp[length]!=-1)
return dp[length]==1;
for(int i=1;i<=length;i++){
String word = target.substring(0,i);
if(arr.contains(word)){
Boolean ans = findAns(arr, n, target.substring(i), dp);
if(ans){
dp[length] = 1;
break;
}else{
dp[length] = 0;
}
}else{
dp[length] = 0;
}
}
return dp[length]==1;
}
}





Comments