Generating all permutations of a given string

前端 未结 30 1618
我寻月下人不归
我寻月下人不归 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:57

    Of all the solutions given here and in other forums, I liked Mark Byers the most. That description actually made me think and code it myself. Too bad I cannot voteup his solution as I am newbie.
    Anyways here is my implementation of his description

    public class PermTest {
    
        public static void main(String[] args) throws Exception {
            String str = "abcdef";
            StringBuffer strBuf = new StringBuffer(str);
            doPerm(strBuf,0);
        }
    
        private static void doPerm(StringBuffer str, int index){
    
            if(index == str.length())
                System.out.println(str);            
            else { //recursively solve this by placing all other chars at current first pos
                doPerm(str, index+1);
                for (int i = index+1; i < str.length(); i++) {//start swapping all other chars with current first char
                    swap(str,index, i);
                    doPerm(str, index+1);
                    swap(str,i, index);//restore back my string buffer
                }
            }
        }
    
        private  static void swap(StringBuffer str, int pos1, int pos2){
            char t1 = str.charAt(pos1);
            str.setCharAt(pos1, str.charAt(pos2));
            str.setCharAt(pos2, t1);
        }
    }   
    

    I prefer this solution ahead of the first one in this thread because this solution uses StringBuffer. I wouldn't say my solution doesn't create any temporary string (it actually does in system.out.println where the toString() of StringBuffer is called). But I just feel this is better than the first solution where too many string literals are created. May be some performance guy out there can evalute this in terms of 'memory' (for 'time' it already lags due to that extra 'swap')

提交回复
热议问题