-
Notifications
You must be signed in to change notification settings - Fork 0
/
RearrangeCharecters.cpp
112 lines (104 loc) · 2.32 KB
/
RearrangeCharecters.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Rearrange characters
// Given a string S with repeated characters. The task is to rearrange characters in a string such
// that no two adjacent characters are the same.
// Note: The string has only lowercase English alphabets and it can have multiple solutions. Return any one of them.
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// } Driver Code Ends
class Solution
{
public:
struct Key{
int freq; // store frequency of character
char ch;
bool operator<(const Key &k) const
{
return freq < k.freq;
}
};
public:
string rearrangeString(string str)
{
//code here
int n = str.length();
int count[26] = {0};
for (int i = 0 ; i < n ; i++)
count[str[i]-'a']++;
priority_queue< Key > pq;
for (char c = 'a' ; c <= 'z' ; c++)
if (count[c-'a'])
pq.push( Key { count[c-'a'], c} );
str = "" ;
Key prev {-1, '#'} ;
while (!pq.empty())
{
Key k = pq.top();
pq.pop();
str = str + k.ch;
if (prev.freq > 0)
pq.push(prev);
(k.freq)--;
prev = k;
}
if (n != str.length())
return "-1";
else
return str;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
string str;
cin>>str;
Solution ob;
string str1=ob.rearrangeString(str);
int flag=1;
int c[26] = {0};
for(int i=0; i<str.length(); i++)
c[str[i]-'a']+=1;
int f = 0;
int x = (str.length()+1)/2;
for(int i=0; i<26; i++)
{
if(c[i]>x)
f = 1;
}
if(f)
{
if(str1=="-1")
cout<<0<<endl;
else
cout<<1<<endl;
}
else
{
int a[26] = {0};
int b[26] = {0};
for(int i=0; i<str.length(); i++)
a[str[i]-'a']+=1;
for(int i=0; i<str1.length(); i++)
b[str1[i]-'a']+=1;
for(int i=0; i<26; i++)
if(a[i]!=b[i])
flag = 0;
for(int i=0;i<str1.length();i++)
{
if(i>0)
if(str1[i-1]==str1[i])
flag=0;
}
if(flag==1)
cout<<"1\n";
else
cout<<"0\n";
}
}
return 0;
} // } Driver Code Ends