字典序法生成全排列演算法的證明
阿新 • • 發佈:2019-01-10
/** * get the next permutation based on dictionary order method * * @param cur * @return next permutation string, or null if cur is the last */ public static String next(String cur) { String ret = null; if (cur == null) return ret; int strlen = cur.length(); char[] lcur = cur.toLowerCase().toCharArray(); int j = strlen - 2; while (j >= 0 && lcur[j] > lcur[j + 1]) { j--; } if (j < 0) return ret; int k = strlen - 1; while (lcur[k] < lcur[j]) { k--; } // swap lcur[k], lcur[j] char temp = lcur[k]; lcur[k] = lcur[j]; lcur[j] = temp; // reverse lcur[j+1, ..., strlen-1] int low = j + 1; int high = strlen - 1; while (low < high) { temp = lcur[low]; lcur[low] = lcur[high]; lcur[high] = temp; low++; high--; } ret = String.valueOf(lcur); return ret; }