Open LLancelot opened 4 years ago
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: ""
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.
S
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: ""
思路:
代码:
class Solution { public String reorganizeString(String S) { int[] hash = new int[26]; // hash.length = 26 for(int i = 0; i < S.length(); i++) { hash[S.charAt(i) - 'a']++; } int max = 0, letter = 0; for (int i = 0; i < hash.length; i++) { if (hash[i] > max) { max = hash[i]; letter = i; } } if (max > (S.length() + 1) / 2) { return ""; } char[] res = new char[S.length()]; int idx = 0; // 先把最高频字母安排在0,2,4,6....等位置上 while (hash[letter] > 0) { res[idx] = (char) (letter + 'a'); idx += 2; hash[letter]--; } // 对剩下的字母,分别对其安排在1,3,5,7的位置上 for (int i = 0; i < hash.length; i++) { while (hash[i] > 0) { if (idx >= res.length) { // idx重置 idx = 1; } res[idx] = (char) (i + 'a'); idx += 2; hash[i]--; } } return String.valueOf(res); } }
思路:
代码: