permutations of a string using iteration

前端 未结 7 1859
迷失自我
迷失自我 2020-12-16 14:36

I\'m trying to find permutation of a given string, but I want to use iteration. The recursive solution I found online and I do understand it, but converting it to an iterati

7条回答
  •  长情又很酷
    2020-12-16 14:57

        List results = new ArrayList();
        String test_str = "abcd";
        char[] chars = test_str.toCharArray();
        results.add(new String("" + chars[0]));
        for(int j=1; j=0; i--) {
                String str = results.remove(i);
                for(int l=0; l<=str.length(); l++) {
                    results.add(str.substring(0,l) + c + str.substring(l));
                }
            }
        }
        System.out.println("Number of Permutations: " + results.size());
        System.out.println(results);
    

    Example: if we have 3 character string e.g. "abc", we can form permuations as below.

    1) construct a string with first character e.g. 'a' and store that in results.

        char[] chars = test_str.toCharArray();
        results.add(new String("" + chars[0]));
    

    2) Now take next character in string (i.e. 'b') and insert that in all possible positions of previously contsructed strings in results. Since we have only one string in results ("a") at this point, doing so gives us 2 new strings 'ba', 'ab'. Insert these newly constructed strings in results and remove "a".

        for(int i=cur_size-1; i>=0; i--) {
            String str = results.remove(i);
            for(int l=0; l<=str.length(); l++) {
                results.add(str.substring(0,l) + c + str.substring(l));
            }
        }
    

    3) Repeat 2) for every character in the given string.

    for(int j=1; j

    This gives us "cba", "bca", "bac" from "ba" and "cab", "acb" and "abc" from "ab"

提交回复
热议问题