-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path80) Rearrange characters in a String such that no two adjacent characters are same.cpp
81 lines (64 loc) · 1.74 KB
/
80) Rearrange characters in a String such that no two adjacent characters are same.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/******************************************************************************
Rearrange characters in a String such that no two adjacent characters are same
*******************************************************************************/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
struct Key{
int frq;
char ch;
//pripority queue
bool operator< (const Key& k) const{
return frq < k.frq;
}
};//close
void rearrangeString(string str){
int len = str.length();
//check the occurenaces
int cnt[MAX_CHAR] = {0};
for(int i=0; i<len; i++){
//index of charecters
//cout<<cnt[str[i] - 'a']++;
cnt[str[i] - 'a']++;
}
//insert into priority queue
priority_queue<Key> priQueue; //initialize
for(char c = 'a'; c<='z'; c++){
int val = c - 'a';
//cout<<ch - 'a'<<"\n";
if(cnt[val]){
//if exist
priQueue.push(Key{cnt[val], c});//insert into queue
}
}
//empty String
str = "";
Key pre{-1, '#'};
while(!priQueue.empty()){
Key k = priQueue.top();
priQueue.pop();
str = str + k.ch;
//if frequnecy is less
if(pre.frq > 0){
priQueue.push(pre);
}
if(pre.frq > 0){
priQueue.push(pre);
}
(k.frq)--;
pre = k;
}
if(len != str.length()){
cout<<"Not possible"<<endl;
}else{
cout<<str<<endl;
}
}
//main method
int main(){
cout<<"Rearrange characters in a String such that no two adjacent characters are same \n";
string str = "bbbaa";
rearrangeString(str);
return 0;
}