Wednesday, November 30, 2022
HomeJavaLearn how to remedy phrase break downside in Java utilizing dynamic programming?...

Learn how to remedy phrase break downside in Java utilizing dynamic programming? Instance

Downside Assertion:
You’re given a dictionary of phrases and the enter string. Decide enter string could be segmented right into a space-separated sequence of given dictionary phrases.

Word: This query relies on dynamic programming and requested a number of occasions in prime product-based corporations.


         Dict = {i, like, am, boy, e, o, canine, cat, g};

        phrase = “iIikedog”  ——–could be segmented into space-separated phrases——–> i, like, canine

Ask your self that ‘I’, ‘like’, and ‘canine’ are introduced within the dictionary?

Sure, so we will say that the given string could be segmented.

Now let’s take one other instance.

         phrase = “ilikecatsanddog” ——— could be segmented as—–> i, like, cats, and, canine

                                                                                                              i, like, cat, s, and, canine

We will see that the phrases ‘cats’, ‘and’, ‘s’ usually are not current within the dictionary so such a string cannot be segmented into space-separated phrases.

Let’s attempt to remedy it…..

Like one other dynamic programming downside, we are going to create a matrix and can use beforehand calculated outcomes to calculate the present consequence.

Think about the given string as an array like this.


The columns and rows characterize the identical given string within the matrix.

Now let’s attempt to perceive what every cell represents within the matrix.

The cells can have two sorts of values both ‘0’ or ‘1’. Suppose the cells (3,6) and (3,7) have the worth ‘1’ this implies the substrings from 3 to six and three to 7 are current within the given enter dictionary.

If you happen to discover the cell (5,3) and the corresponding substring within the given phrase the course is reverse and there’s no level in contemplating the reverse computation of the given string. So we are going to mark all such cells as ‘0’.

We stuffed half of the matrix with worth ‘0’ so we no must carry out the reverse computations for these cells. This manner we will save each reminiscence and time.

Now begin filling remainder of the cells manually by evaluating the row-column pair worth in opposition to the given dictionary.

So the cell (0, 0) i.e. ‘i’ is current within the dictionary so matrix[0][0] = 1.

Equally cell (4, 4) i.e. ‘e’ can also be current within the dictionary so matrix[4][4] = 1.

Now let’s take one substring ‘ilike’ and see the logic to resolve this downside.


          i      l     i     ok      e

          0     1    2    3      4

We’ll attempt to separate this string into 2 elements in all of the doable methods.

Let say we now have first 2 elements: 

(0, 0)——–> ‘i’ and (1, 1)———-> ‘l’ 

matrix[0][0] && matrix[1][1]

                  1 && 0

So ‘il‘ isn’t current within the dictionary.

Think about one other mixture.

(4, 3)——–> ‘ok’ and (4, 4)———-> ‘e’ 

matrix[4][3] && matrix[4][4]

                  0 && 1

That is false means ‘ke’ isn’t current within the dictionary.

So I’ll carry on taking the substrings from the given phrase to be area separated and divide them into 2 elements in several methods and can verify in opposition to the matrix that if each the elements are true i.e. ‘1’ means the substring is current within the dictionary.

So lastly we are going to take into account your complete given phrase and divide it into 2 elements in all of the doable methods and we are going to use the values of the beforehand computed cells to calculate the worth of the marked cell and if the the worth is ‘1’ means the given phrase could be separated into the area separated segments.

Begin Implementing it…

Think about beneath code snippet.

       For i = 0 and N = 7

      for(int ok = 0; ok < N+1; ok++){

              if(matrix[i][i+k]) && matrix[k+1][N])


                    return true;



The if situation exhibits the logic to divide the given phrase into 2 elements in all doable methods.

Full Code:

public class Predominant {


    public String wordBreakProblem(String phrase, Set<String> dict){

            int matrix[][] = new int[word.length()][word.length()];


// failing all of the cells with ‘-1’.

            for(int i=0; i < matrix.size; i++){

                for(int j=0; j < matrix[i].size ; j++){

                    matrix[i][j] = -1; 





//If the substring is current within the dictionary then fill the corresponding cell with non-negative worth.

            for(int l = 1; l <= phrase.size(); l++){

                for(int i=0; i < phrase.size() -l + 1 ; i++){

                    int j = i + l-1;

                    String str = phrase.substring(i,j+1);



                        matrix[i][j] = i;




// Filling the worth of the corresponding cell for the taken substring utilizing worth of the beforehand calculated cell.

                    for(int ok=i+1; ok <= j; ok++){

                        if(matrix[i][k-1] != -1 && matrix[k][j] != -1){

                            matrix[i][j] = ok;






            if(matrix[0][word.length()-1] == -1){

                return null;




//Lastly segregate the given phrase into the phrases obtainable within the dictionary.

            StringBuffer buffer = new StringBuffer();

            int i = 0; int j = phrase.size() -1;

            whereas(i < j){

                int ok = matrix[i][j];

                if(i == ok){

                    buffer.append(phrase.substring(i, j+1));



                buffer.append(phrase.substring(i,ok) + ” “);

                i = ok;



            return buffer.toString();


        public static void principal(String args[]){

            Set<String> dictionary = new HashSet<String>();






            String str = “Ihadliketoplay”;

            Predominant bmw = new Predominant();

            String result1 = bmw.wordBreakProblem(str, dictionary);






I had prefer to play

Take a look at your understanding…

Q. 1) Given dict = {‘li, ‘sop’, ‘tree’, ‘ding’, ‘g’} and phrase = ‘sopptreeg’. Is it doable to section the given string into area separated segments of the given dict. phrases ?

Ans. ‘sop’ , ‘p’, ‘tree’, ‘g’

‘so’, ‘pp’, ‘tree’, ‘g’

It seems just like the given phrase cannot be separated.

Earlier than you allow…

Information of information construction and algorithms is should to simulate the actual world downside in code.

If you wish to be taught extra about this text, drop a remark beneath and attain out to us to tell us your curiosity.

If you happen to loved studying the basics of DSA share your information to your fellow programmers and social circle. Could also be somebody out actually wants this useful resource, and also you is perhaps serving to them out by sharing it.




Please enter your comment!
Please enter your name here

Most Popular

Recent Comments