LeetCode 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]
.
题解:
In order to makie adjacent chars different from each other, we need to find the most frequent char and arrange it first.
If the frequency of most frequent char is > (S.length()+1)/2, that means there is no way to arrange without putting 2 most frequent char adjacent, return "".
Otherwise, arrange most prequent char first starting from index 0, index += 2.
After this, place the rest chars starting from current index and when index hit the end, reset it to 1.
Time Complexity: O(n). n =S.length.
Space: O(n).
AC Java:
1 class Solution { 2 public String reorganizeString(String S) { 3 if(S == null || S.length() == 0){ 4 return S; 5 } 6 7 int n = S.length(); 8 int [] map = new int[26]; 9 int maxCount = 0; 10 char maxChar = 'a'; 11 for(char c : S.toCharArray()){ 12 map[c - 'a']++; 13 if(map[c - 'a'] > maxCount){ 14 maxChar = c; 15 maxCount = map[c - 'a']; 16 } 17 } 18 19 if(maxCount > (n + 1) / 2){ 20 return ""; 21 } 22 23 int i = 0; 24 char [] res = new char[n]; 25 while(map[maxChar - 'a'] > 0){ 26 res[i] = maxChar; 27 i += 2; 28 map[maxChar - 'a']--; 29 } 30 31 for(int k = 0; k < 26; k++){ 32 while(map[k] > 0){ 33 if(i >= n){ 34 i = 1; 35 } 36 37 res[i] = (char)('a' + k); 38 i += 2; 39 map[k]--; 40 } 41 } 42 43 return new String(res); 44 } 45 }