767.Reorganize-String

767. Reorganize String

题目地址

https://leetcode.com/problems/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]

代码

Approach 1: Sort by Count

Complexity Analysis

1 3 5 7 9...

0 2 4 6 8...

  • Time Complexity: O(A(_N+logA)), where N is the length of _S, and A is the size of the alphabet. In Java, our implementation is O_(_N+AlogA). If A is fixed, this complexity is O(N).

  • Space Complexity: O(N). In Java, our implementation is O_(_N+A).

class Solution {
  public String reorganizeString(String S) {
    int N = S.length();
    int[] counts = new int[26];
    for (char c : S.toCharArray()) {
      counts[c - 'a'] += 100;
    }
    for (int i = 0; i < 26; i++) {
      counts[i] += i;
    }

    Arrays.sort(counts);

    char[] ans = new char[N];
    int t = 1;
    for (int code : counts) {
      int ct = code / 100;
      char ch = (char) ('a' + (code % 100));
      if (ct > (N + 1) / 2) return "";
      for (int i = 0; i < ct; i++) {
        if (t >= N) t = 0;
        ans[t] = ch;
        t += 2;
      }
    }

    return String.valueOf(ans);
  }
}

Approach #2 Greedy with Heap

Complexity Analysis

  • Time Complexity: O(_N_logA)), where N is the length of S, and A is the size of the alphabet. If A is fixed, this complexity is O(N).

  • Space Complexity: O(A). If A is fixed, this complexity is O(1).

class Solution {
  public String reorganizeString(String S) {
    int N = S.length();
    int[] count = new int[26];
    for (char c : S.toCharArray()) {
      count[c - 'a']++;
    }
    PriorityQueue<MultiChar> pq = new PriorityQueue<MultiChar((a, b) -> a.count == b.count ? a.letter - b.letter : b.count - a.count);

    for (int i = 0; i < 26; i++) {
      if (count[i] > (N + 1) / 2) return "";

      pq.add(new MultiChar(count[i], (char) ('a' + i)));
    }

    StringBuilder ans = new StringBuilder();
    while (pq.size() >= 2) {
      MultiChar mc1 = pq.poll();
      MultiChar mc2 = pq.poll();

      ans.append(mc1.letter);
      ans.append(mc2.letter);
      if (--mc1.count > 0) pq.add(mc1);
      if (--mc2.count > 0) pq.add(mc2);
    }

    if (pq.size() > 0) ans.append(pq.poll().letter);
    return ans.toString();
  }
}

class MultiChar {
  int countP
  char letter;
  MultiChar(int ct, char ch) {
    count = ct;
    letter = ch;
  }
}

Last updated