Reorganize String

LeetCode Q 767 - Reorganize String

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.

If possible, output any possible result. If not possible, return the empty string.

Example 1: Input: S = "aab" ; Output: "aba"

Example 2: Input: S = "aaab" ; Output: ""

Note: S will consist of lowercase letters and have length in range [1, 500].

Solution

Code: Version 1

public String reorganizeString(String S) {
	
	int[] count = new int[26];
	
	for (char ch: S.toCharArray()) {
		count[ch - 'a']++;
		if (count[ch - 'a'] > (S.length() + 1) / 2) return "";
	}

	PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (b[1] - a[1]));

	for (int i = 0; i < 26; i++) {
		if (count[i]) > 0
			pq.offer(new int[] {i, count[i]});
	}
	
	StringBuilder sb = new StringBuilder();

	while (!pq.isEmpty) {
		int[] curr = pq.poll();

		if (sb.length() == 0 || sb.charAt(sb.length() - 1) != (char)(curr[0] + 'a')) {
			sb.append((char)(curr[0] + 'a'));
			if (--curr[1] > 0)
				pq.offer(curr);
		} else {
			int[] next = pq.poll();
			sb.append((char)(next[0] + 'a'))
			if (--next[1] > 0)
				pq.offer(next);
			pq.offer(curr);
		}
	}

	return sb.toString();
}

Code: Version 2 More Concise

public String reorganizeString(String S) {
	
	int[] count = new int[26];
	
	for (char ch: S.toCharArray()) {
		count[ch - 'a']++;
	}

	PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (b[1] - a[1]));

	for (int i = 0; i < 26; i++) {
		if (count[i]) > 0
			pq.offer(new int[] {i, count[i]});
	}
	
	StringBuilder sb = new StringBuilder();
	int[] prev = {-1, 0};

	while (!pq.isEmpty) {
		int[] curr = pq.poll();
		if (prev[1] > 0) pq.offer(prev);
		sb.append((char)(curr[0] + 'a')); // add back last used character
		curr[1]--;
		prev = curr; // set this character as previous used

		// if we left with anything return ""
		if (pq.isEmpty() && prev[1] > 0) return "";
	}

	return sb.toString();
}

   Reprint policy


《Reorganize String》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC