1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| private void swap(StringBuilder sb, int i, int j) { char c = sb.charAt(i); sb.setCharAt(i, sb.charAt(j)); sb.setCharAt(j, c); }
private void reverse(StringBuilder sb, int start, int end) { int mid = (end - start + 1) / 2; for(int i = 0; i < mid; ++i) { char c = sb.charAt(start + i); sb.setCharAt(start + i, sb.charAt(end - i)); sb.setCharAt(end - i, c); } }
public String nextPermutation(StringBuilder sb, int cnt, int k) { while(cnt < k) { ++cnt; int i = sb.length() - 1; while(i - 1 >= 0 && sb.charAt(i) <= sb.charAt(i - 1)) --i; if(i <= 0) { reverse(sb, 0, sb.length() - 1); continue; } int j = sb.length() - 1; while(j > i - 1 && sb.charAt(j) <= sb.charAt(i - 1) ) --j; swap(sb, j, i - 1); reverse(sb, i, sb.length() - 1); } return new String(sb); }
|