查找单词中所有非重复字母的排列

给定3个唯一字母:您是否可以使用递归函数打印字母的六个可能的非重复组合。“ cat”应输出:cat,act,atc,tac,tca和cta。这是我的程序,找不到递归算法。这是我的尝试:


 static void findWords(StringBuilder string, int start, int stride) {

    //1. iterate through all possible combinations of the chars recursively


    System.out.println(string);


    if (stride < string.length() && start < string.length())

    {

        char temp = string.charAt(stride);

        string.setCharAt(stride, string.charAt(start));

        string.setCharAt(start, temp);


        findWords(string, start, stride + 1);


        findWords(string, start + 1, stride + 1 );



    }

}


public static void main(String[] args)

{


   StringBuilder word = new StringBuilder("cat");

   findWords(word,0,1);

}


蓝山帝景
浏览 148回答 3
3回答

慕尼黑的夜晚无繁华

我使用的算法非常简单。将每个字符设为字符串的第一个字符,然后查找与其他两个字符的组合。因此,对于字符c,a,t,组合为c atc taa cta tct cat ac代码:static void findWords(String str, int pos) {&nbsp; &nbsp; if(str == null || pos < -1) {&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; int len = str.length();&nbsp; &nbsp; if(pos + 1 < len) {&nbsp; &nbsp; &nbsp; &nbsp; findWords(str, pos + 1);&nbsp; &nbsp; }&nbsp; &nbsp; //find char swap positions&nbsp; &nbsp; int pos1 = (pos + 1) % len;&nbsp; &nbsp; int pos2 = (pos - 1 + len) % len;&nbsp; &nbsp; char[] chars = str.toCharArray();&nbsp; &nbsp; String str1 = new String(new char[] {chars[pos], chars[pos1], chars[pos2]});&nbsp; &nbsp; String str2 = new String(new char[] {chars[pos], chars[pos2], chars[pos1]});&nbsp; &nbsp; System.out.println(str1);&nbsp; &nbsp; System.out.println(str2);}public static void main(String[] args) {&nbsp; &nbsp; String word = new String("abc");&nbsp; &nbsp; findWords(word, 0);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java