Leetcode 767. Reorganize String
Given a string s
, rearrange the characters of s
so that any two adjacent characters are not the same.
Return any possible rearrangement of s
or return an empty string if not possible.
s
?
s
purely lowercase English letters?
s
.O(log n)
.n
times, the overall time complexity is O(n log n)
where n
is the length of the string s
.Here’s the implementation in C++:
#include <iostream>
#include <string>
#include <unordered_map>
#include <queue>
#include <vector>
using namespace std;
string reorganizeString(string s) {
// Step 1: Count the frequency of each character.
unordered_map<char, int> freq;
for(char c : s) {
freq[c]++;
}
// Step 2: Put characters into a max-heap based on their frequency.
priority_queue<pair<int, char>> maxHeap;
for(auto& entry : freq) {
maxHeap.push({entry.second, entry.first});
}
// Step 3: Build the resulting string.
string result = "";
pair<int, char> prev(0, '#');
while(!maxHeap.empty()) {
auto current = maxHeap.top();
maxHeap.pop();
// Append current character to the result.
result += current.second;
// If the previous character has more frequency left, push it back to the heap.
if(prev.first > 0) {
maxHeap.push(prev);
}
// Update previous with the current (but reduce the frequency).
current.first--;
prev = current;
}
// Final check to make sure the rearrangement is valid.
for(int i = 1; i < result.size(); ++i) {
if(result[i] == result[i-1]) {
return "";
}
}
return result;
}
// Example usage
int main() {
string s = "aab";
cout << reorganizeString(s) << endl; // Possible output: "aba"
s = "aaab";
cout << reorganizeString(s) << endl; // Possible output: ""
return 0;
}
Feel free to ask any questions or request clarifications on the above solution!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?