简体   繁体   中英

Permutations Code not working Java

My teacher gave me some java code and asked me to rewrite it in python. I'm not asking for help with rewriting it, but when I entered the code into my Java compiler I got this error:

Exception in thread "main" java.lang.StackOverflowError
    at 
java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at java.lang.StringBuilder.<init>(StringBuilder.java:113)
at Permutations.perm1(Permutations.java:12)
at Permutations.perm1(Permutations.java:4) 

Any help is greatly appreciated, here is the code:

public class Permutations {
public static void perm1(String s) {
    perm1("", s);
}
private static void perm1(String prefix, String s){
    int N=s.length();
    if(N==0){
        System.out.println(prefix);
    }else{
        for(int i=0; i<N; i++){
            perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1, 
N));
        }
    }
}
public static void perm2(String s){
    int N=s.length();
    char[] a = new char[N];
    for(int i=0;i<N;i++){
        a[i]=s.charAt(i);
        perm2(a,N);
    }
}
private static void perm2(char[] a, int n){
    if(n==1){
        System.out.println(a);
        return;
    }
    for(int i=0; i<n;i++){
        swap(a,i,n-1);
        perm2(a,n-1);
        swap(a,i,n-1);
    }
}
private static void swap(char[] a, int i, int j) {
    char c;
    c=a[i];
    a[i]=a[j];
    a[j]=c; 
 }
    public static void main(String[] args) {
 int N=5;
String alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0,N);
perm1(elements);
System.out.println();
perm2(elements);
    }

}

Stepping through the code with a debugger shows that you get a stack overflow error because of this section:

for(int i=0; i<N; i++){
        perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N));
}

perm1 is called repeatedly, but the input doesn't change - it's always passed "abcde" with no prefix, and the result of prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N) is still "abcde" . Since the call is recursive, and the input doesn't change with each iteration, it just repeats and takes up increasingly more space on the stack until it overflows and throws an exception.

There is an error in this line:

perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1, 
N));

Should look like this:

perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, N));

Compere with this code: http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM