permutations of a string using iteration

前端 未结 7 1844
迷失自我
迷失自我 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:49

    import java.util.List;
    import java.util.Set;
    import java.util.ArrayList;
    import java.util.HashSet;
    
    public class Anagrams{
    
        public static void main(String[] args)
        {
    
            String inpString = "abcd";
            Set combs = getAllCombs(inpString);
    
            for(String comb : combs)
            {
                System.out.println(comb);
            }
    
        }
    
    
        private static Set getAllCombs(String inpString)
        {
            Set combs = new HashSet();
            if( inpString == null | inpString.isEmpty())
                return combs;
    
            combs.add(inpString.substring(0,1));
            Set tempCombs = new HashSet();
            for(char a : inpString.substring(1).toCharArray())
            {
                tempCombs.clear();
                tempCombs.addAll(combs);
                combs.clear();
                for(String comb : tempCombs)
                {
                    combs.addAll(getCombs(comb,a));
                }
            }
            return combs;
        }
    
        private static Set getCombs(String comb, char a) {
            Set combs = new HashSet();
            for(int i = 0 ; i <= comb.length(); i++)
            {
                String temp = comb.substring(0, i) + a + comb.substring(i);
                combs.add(temp);
                //System.out.println(temp);
            }
            return combs;
        }   
    }
    

提交回复
热议问题