【问题标题】:String permutations using recursive method and Java [duplicate]使用递归方法和Java的字符串排列[重复]
【发布时间】:2015-02-20 02:10:55
【问题描述】:

到目前为止,我的代码似乎让我得到了正确的结果。除了我遇到了问题。当我给它一个长度为 8 个字符或更长的字符串时,它似乎没有结束。我已经有 30 亿个排列,它还在运行。当我尝试使用较短字符串的方法时,它终止并给出了正确的输出。我不知道还能尝试什么,我会很感激任何提示。这是Java代码:

public static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) {
        permutations++;
        System.out.println(prefix);
        System.out.println("Permutations: " + permutations);
    } else {
        for (int i = 0; i < n; i++) {
            permutation(prefix + str.charAt(i),
                    str.substring(0, i) + str.substring(i + 1));
        }
    }
}

【问题讨论】:

    标签: java string recursion permutation


    【解决方案1】:

    此代码适用于 Windows 8 和 java 1.8。示例字符串有 9 个字符长,并产生预期的结果。我不确定您是如何声明“排列”的,但我只是使用了一个 int,除非您使用超过 12 个字符的字符串,否则它应该对您有用。顺便说一句,我没有更改您的任何代码。听起来您正在做其他事情,而不仅仅是打印出这些排列,所以您的问题可能出在您的另一段代码上?

    public class example{
       public static int permutations = 0;
       public static void main(String[] args){
          String myS = "abcdefghi";
          perms(myS);
          System.out.println(myS.length());
       }
       public static void perms(String s){
          permutation("",s);
       }
       public static void permutation(String prefix, String str){
          int n = str.length();
          if (n == 0){
             permutations++;
             System.out.println(prefix);
             System.out.println("Permutations: " + permutations);
          } else {
             for (int i = 0; i < n; i++){
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1));
             } 
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-22
      • 2014-12-03
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 2018-04-05
      • 1970-01-01
      相关资源
      最近更新 更多