Question:
How to determine the number of valid groupings for a string using Java

Summary

Let’s assume the method name TotalCount and the objective of this method is to count the total number of substrings in the input string ‘str’. The sum of the digit in the substrings is equal to or greater than the sum of the digits of the previous substring. 


Solution

//User function Template for Java


class Solution

{

    public int TotalCount(String str)

    {

        // Code here

        int[][] dp=new int[101][1000];

        for(int i=0;i<dp.length;i++){

            Arrays.fill(dp[i],-1);

        }

        return find(str,0,0,dp);

        

    }

    

    public int find(String s,int pos,int psum,int[][] dp ){

        if(pos>=s.length()){

            return 1;

        }

        

        if(dp[pos][psum]!=-1){

            return dp[pos][psum];

        }


        int csum=0;

        int res=0;

        for(int i=pos;i<s.length();i++){

            csum+=s.charAt(i)-'0';

            if(csum>=psum){

                res+=find(s,i+1,csum,dp); 

            }

        }

                dp[pos][psum]=res;

                return res;

    }

}


Explanation

  • In the above code, the TotalCount method initializes a 2D array. To show that the results have not yet been calculated, the array is filled with -1.

  • The input string str, the current position pos in the string, the previous sum psum, and the memoization array dp are passed to the helper function named find by the TotalCount method.

  • The total count of valid substrings that satisfy the given condition is determined by the recursive function known as the find method.

  • If the current position pos is beyond the length of the string s, the function returns 1, indicating the end of the string.


Answered by:> >gujjulassr

Credit:> >GeekforGeeks


Suggested blogs:

>How to configure python in jmeter?

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers