Generating all permutations of a given string

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

    This one is without recursion

    public static void permute(String s) {
        if(null==s || s.isEmpty()) {
            return;
        }
    
        // List containing words formed in each iteration 
        List strings = new LinkedList();
        strings.add(String.valueOf(s.charAt(0))); // add the first element to the list
    
         // Temp list that holds the set of strings for 
         //  appending the current character to all position in each word in the original list
        List tempList = new LinkedList(); 
    
        for(int i=1; i< s.length(); i++) {
    
            for(int j=0; j merge(Character c,  String s) {
        if(s==null || s.isEmpty()) {
            return null;
        }
    
        int len = s.length();
        StringBuilder sb = new StringBuilder();
        Set list = new HashSet();
    
        for(int i=0; i<= len; i++) {
            sb = new StringBuilder();
            sb.append(s.substring(0, i) + c + s.substring(i, len));
            list.add(sb.toString());
        }
    
        return list;
    }
    

提交回复
热议问题