Find all the combination of substrings that add up to the given string

前端 未结 5 726
渐次进展
渐次进展 2021-01-02 11:05

I\'m trying to create a data structure that holds all the possible substring combinations that add up to the original string. For example, if the string is \"java\"

5条回答
  •  天涯浪人
    2021-01-02 11:41

    Here's one approach:

    static List> substrings(String input) {
    
        // Base case: There's only one way to split up a single character
        // string, and that is ["x"] where x is the character.
        if (input.length() == 1)
            return Collections.singletonList(Collections.singletonList(input));
    
        // To hold the result
        List> result = new ArrayList<>();
    
        // Recurse (since you tagged the question with recursion ;)
        for (List subresult : substrings(input.substring(1))) {
    
            // Case: Don't split
            List l2 = new ArrayList<>(subresult);
            l2.set(0, input.charAt(0) + l2.get(0));
            result.add(l2);
    
            // Case: Split
            List l = new ArrayList<>(subresult);
            l.add(0, input.substring(0, 1));
            result.add(l);
        }
    
        return result;
    }
    

    Output:

    [java]
    [j, ava]
    [ja, va]
    [j, a, va]
    [jav, a]
    [j, av, a]
    [ja, v, a]
    [j, a, v, a]
    

提交回复
热议问题