簡體   English   中英

My String Permutations算法不起作用

[英]My String Permutations algorithm doesn't work

我編寫了一個求解字符串置換算法的算法。 它有一個問題,它在某處打印錯誤的輸出。 我已經多次遍歷我的代碼以獲得不同的輸入,但我無法找到我所做的錯誤。

有人會解釋我犯了什么錯嗎?

public static void main(String args[]) throws Exception {

    String str1 = "eat";
    int len = str1.length();
    char[] str = str1.toCharArray();
    recurPerm(str,0,len);
}
static void recurPerm(char[] str, int strstartind, int sz) {

    for(int i = strstartind; i < sz; i++){
        if(i > strstartind) {

            char temp = str[strstartind];
            str[strstartind] = str[i];
            str[i] = temp;

            recurPerm(str, strstartind + 1, sz);
        }
        else {
            recurPerm(str, strstartind + 1, sz);
        }
    }
    if(strstartind >= sz){
        System.out.println(str);
    }

    return;
}

產量

eat
eta
tea 
tae
eat
eta

但正確的輸出是

吃eta aet吃了茶

我也嘗試過調試。 我發現調試太難了,因為涉及到遞歸。

您應該恢復遞歸的原始狀態,否則您將繼續混合給定的參數。 函數參數“strstartind”僅指示要選擇的正確char,如果原始“str []”未更改,但是您在以下位置覆蓋原始“str []”:

    str[strstartind] = str[i];
    str[i] = temp;

這是一個有效的解決方案,它可以恢復遞歸參數:

public class DemoApplicationTests {

public static void main(String args[]) throws Exception {

    String str1 = "eat";
    int len = str1.length();
    char[] str = str1.toCharArray();
    recurPerm(str, 0, len);
}

static void recurPerm(char[] str, int strstartind, int sz) {

    for (int i = strstartind; i < sz; i++) {
        char temp = str[strstartind];
        str[strstartind] = str[i];
        str[i] = temp;
        recurPerm(str, strstartind + 1, sz);
        //restore state
        str[i] = str[strstartind];
        str[strstartind] = temp;
    }
    if (strstartind >= sz) {
        System.out.println(str);
    }

    return;
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM