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

前端 未结 5 729
渐次进展
渐次进展 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:43

    A different recursive solution that just adds to the list results

    static List> substrings(String input) {
        List> result = new ArrayList<>();
        if (input.length() == 1) {
            result.add(Arrays.asList(new String[]{input}));
        }
        else {
            //iterate j, ja, jav, jav
            for (int i = 0; i < input.length()-1; i++ ) {
                String root = input.substring(0,i+1);
                String leaf = input.substring(i+1);
                for( List strings: substrings(leaf) ) {
                    ArrayList current = new ArrayList();
                    current.add(root);
                    current.addAll(strings);
                    result.add(current);
                }
            }
            //adds the whole string as one of the leaves (ie. java, ava, va, a)
            result.add(Arrays.asList(new String[]{input}));
        }
        return result;
    }
    

提交回复
热议问题