767 Reorganize String

1. Question

Given a stringS, 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:

  • Swill consist of lowercase letters and have length in range[1, 500].

2. Implementation

(1) Greedy

3. Time & Space Complexity

Greedy: 时间复杂度O(nlogn), n是S的长度, 空间复杂度O(n)

Last updated

Was this helpful?