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
| class Solution { public String sortString(String s) { char[] ch = s.toCharArray(); Arrays.sort(ch); int n = ch.length; boolean[] st = new boolean[n]; StringBuilder sb = new StringBuilder();
while (sb.length() != n) { char pre = 'A'; for (int k = 0; k < n; k++) { if (!st[k] && ch[k] != pre){ sb.append(ch[k]); st[k] = true; pre = ch[k]; } } pre = 'A'; for (int k = n-1; k >= 0; k--) { if (!st[k] && ch[k] != pre){ sb.append(ch[k]); st[k] = true; pre = ch[k]; } } } return sb.toString(); } }
|