We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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); } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
思路:
代码:
The text was updated successfully, but these errors were encountered: