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: ""

 1 class Solution {
 2     public String reorganizeString(String S) {
 3         int[] hash = new int[26];
 4         for (int i = 0; i < S.length(); i++) {
 5             hash[S.charAt(i) - 'a']++;
 6         } 
 7         int max = 0, letter = 0;
 8         for (int i = 0; i < hash.length; i++) {
 9             if (hash[i] > max) {
10                 max = hash[i];
11                 letter = i;
12             }
13         }
14         if (S.length() - max < max - 1) {
15             return ""; 
16         }
17         char[] res = new char[S.length()];
18         int idx = 0;
19         while (hash[letter] > 0) {
20             res[idx] = (char) (letter + 'a');
21             idx += 2;
22             hash[letter]--;
23         }
24         
25         for (int i = 0; i < hash.length; i++) {
26             // we need to continue with idx set at line 21.
27             while (hash[i] > 0) {
28                 if (idx >= res.length) {
29                     idx = 1;
30                 }
31                 res[idx] = (char) (i + 'a');
32                 idx += 2;
33                 hash[i]--;
34             }
35         }
36         return String.valueOf(res);
37     }
38 }

 

posted @ 2021-03-29 06:23  北叶青藤  阅读(55)  评论(0编辑  收藏  举报