Generating all permutations of a given string

前端 未结 30 1616
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  [愿得一人]
    2020-11-21 06:56

    this worked for me..

    import java.util.Arrays;
    
    public class StringPermutations{
        public static void main(String args[]) {
            String inputString = "ABC";
            permute(inputString.toCharArray(), 0, inputString.length()-1);
        }
    
        public static void permute(char[] ary, int startIndex, int endIndex) {
            if(startIndex == endIndex){
                System.out.println(String.valueOf(ary));
            }else{
                for(int i=startIndex;i<=endIndex;i++) {
                     swap(ary, startIndex, i );
                     permute(ary, startIndex+1, endIndex);
                     swap(ary, startIndex, i );
                }
            }
        }
    
        public static void swap(char[] ary, int x, int y) {
            char temp = ary[x];
            ary[x] = ary[y];
            ary[y] = temp;
        }
    }
    

提交回复
热议问题