leetcode 767. Reorganize String | 767. 重构字符串(贪心+分桶+26路归并)

x33g5p2x  于2021-12-03 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(307)

题目

https://leetcode.com/problems/reorganize-string/

题解

分桶策略,和两个月之前做的 621.Task Scheduler 类似。

两个月之前看的答案还有印象,如果是三个月之前,就说不准了。。

  1. class Solution {
  2. public String reorganizeString(String s) {
  3. int L = s.length();
  4. int[][] count = new int[26][2];
  5. for (int i = 0; i < 26; i++) {
  6. count[i][1] = i;
  7. }
  8. for (int i = 0; i < L; i++) {
  9. count[s.charAt(i) - 'a'][0]++;
  10. }
  11. Arrays.sort(count, (o1, o2) -> o2[0] - o1[0]);
  12. // 贪心地按行平铺到桶内。桶的宽度,是出现最多的字母的出现次数
  13. int N = count[0][0];
  14. int[][] bucket = new int[L / N + 1][N];
  15. for (int[] r : bucket) {
  16. Arrays.fill(r, -1);
  17. }
  18. int total = 0;
  19. for (int i = 0; i < 26; i++) {
  20. for (int j = 0; j < count[i][0]; j++) {
  21. bucket[total / N][total % N] = count[i][1];
  22. total++;
  23. }
  24. }
  25. // 26路归并
  26. StringBuilder res = new StringBuilder();
  27. for (int j = 0; j < N; j++) {
  28. for (int i = 0; i < bucket.length; i++) {
  29. if (bucket[i][j] >= 0) {
  30. res.append((char) ('a' + bucket[i][j]));
  31. }
  32. }
  33. }
  34. if (res.charAt(L - 1) == res.charAt(L - 2)) return "";
  35. return res.toString();
  36. }
  37. }

相关文章