|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.PriorityQueue; |
| 6 | + |
| 7 | +/** |
| 8 | + * 767. Reorganize String |
| 9 | + * |
| 10 | + * Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. |
| 11 | +
|
| 12 | + If possible, output any possible result. If not possible, return the empty string. |
| 13 | +
|
| 14 | + Example 1: |
| 15 | +
|
| 16 | + Input: S = "aab" |
| 17 | + Output: "aba" |
| 18 | +
|
| 19 | + Example 2: |
| 20 | +
|
| 21 | + Input: S = "aaab" |
| 22 | + Output: "" |
| 23 | +
|
| 24 | + Note: |
| 25 | +
|
| 26 | + S will consist of lowercase letters and have length in range [1, 500]. |
| 27 | + */ |
| 28 | + |
| 29 | +public class _767 { |
| 30 | + public static class Solution1 { |
| 31 | + public String reorganizeString(String S) { |
| 32 | + Map<Character, Integer> map = new HashMap<>(); |
| 33 | + for (char c : S.toCharArray()) { |
| 34 | + map.put(c, map.getOrDefault(c, 0) + 1); |
| 35 | + } |
| 36 | + int len = S.length(); |
| 37 | + for (char c : map.keySet()) { |
| 38 | + if ((len % 2 == 0 && map.get(c) > len / 2) || (len % 2 != 0 && map.get(c) >= len / 2 + 2)) { |
| 39 | + return ""; |
| 40 | + } |
| 41 | + } |
| 42 | + PriorityQueue<CustChar> queue = new PriorityQueue<>((a, b) -> b.count - a.count); |
| 43 | + for (char c : map.keySet()) { |
| 44 | + queue.offer(new CustChar(c, map.get(c))); |
| 45 | + } |
| 46 | + |
| 47 | + StringBuilder sb = new StringBuilder(); |
| 48 | + while (!queue.isEmpty()) { |
| 49 | + CustChar curr = queue.poll(); |
| 50 | + char c = curr.c; |
| 51 | + if (sb.length() > 0 && sb.charAt(sb.length() - 1) != c) { |
| 52 | + sb.append(c); |
| 53 | + if (curr.count > 1) { |
| 54 | + queue.offer(new CustChar(c, curr.count - 1)); |
| 55 | + } |
| 56 | + } else if (sb.length() == 0) { |
| 57 | + sb.append(c); |
| 58 | + if (curr.count > 1) { |
| 59 | + queue.offer(new CustChar(c, curr.count - 1)); |
| 60 | + } |
| 61 | + } else if (sb.length() > 0 && sb.charAt(sb.length() - 1) == c && !queue.isEmpty()) { |
| 62 | + CustChar next = queue.poll(); |
| 63 | + sb.append(next.c); |
| 64 | + if (next.count > 1) { |
| 65 | + queue.offer(new CustChar(next.c, next.count - 1)); |
| 66 | + } |
| 67 | + queue.offer(curr); |
| 68 | + } |
| 69 | + } |
| 70 | + return sb.toString(); |
| 71 | + } |
| 72 | + |
| 73 | + class CustChar { |
| 74 | + Character c; |
| 75 | + int count; |
| 76 | + |
| 77 | + public CustChar(Character c, int count) { |
| 78 | + this.c = c; |
| 79 | + this.count = count; |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments