All ways to partition a string

后端 未结 5 1961
深忆病人
深忆病人 2021-01-01 00:08

I\'m trying to find a efficient algorithm to get all ways to partition a string

eg for a given string \'abcd\' =>
\'a\' \'bcd\'
\'a\' \'b\' \'cd\'
\'a\'

5条回答
  •  别那么骄傲
    2021-01-01 00:43

    GeeksforGeeks has provided a well-explained solution to this problem:

    For string abcd there will be 2^(n-1) i.e. 8 partitions.

    (a)(b)(c)(d)
    (a)(b)(cd)
    (a)(bc)(d)
    (a)(bcd)
    (ab)(c)(d)
    (ab)(cd)
    (abc)(d)
    (abcd)
    

    The crux of the solution lies in the recursion to print all the permutations.
    maintain two parameters – index of the next character to be processed and the output string so far. We start from index of next character to be processed, append substring formed by unprocessed string to the output string and recurse on remaining string until we process the whole string.

    // Java program to find all combinations of Non-
    // overlapping substrings formed from given
    // string
    
    class GFG 
    {
        // find all combinations of non-overlapping
        // substrings formed by input string str
        static void findCombinations(String str, int index,
                                     String out)
        {
            if (index == str.length())
                System.out.println(out);
    
            for (int i = index; i < str.length(); i++)
    
                // append substring formed by str[index,
                // i] to output string
                findCombinations(str, i + 1, out +
                    "(" + str.substring(index, i+1) + ")" );
        }
    
        // driver program
        public static void main (String[] args) 
        {
            // input string
            String str = "abcd";
            findCombinations(str, 0, "");
        }
    }
    

    Time Complexity is O(2^n)

    Here's the link to the article: http://www.geeksforgeeks.org/print-ways-break-string-bracket-form/

提交回复
热议问题