FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/RearrangeKDistanceApart.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
RearrangeKDistanceApart.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
51 lines (45 loc) · 1.31 KB
Breadcrumbs
coding-Interview
/
RearrangeKDistanceApart.java
Copy path
File metadata and controls
51 lines (45 loc) · 1.31 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/**
*
* Example 1:
Input: s = "aabbcc", k = 3
Output: "abcabc"
Explanation: The same letters are at least a distance of 3 from each other.
Example 2:
Input: s = "aaabc", k = 3
Output: ""
Explanation: It is not possible to rearrange the string.
Example 3:
Input: s = "aaadbbcc", k = 2
Output: "abacabcd"
Explanation: The same letters are at least a distance of 2 from each other.
**/
class
Solution
{
public
String
rearrangeString
(
String
s
,
int
k
) {
int
n
=
s
.
length
();
int
[]
cnt
=
new
int
[
26
];
for
(
char
c
:
s
.
toCharArray
()) {
++
cnt
[
c
-
'a'
];
}
PriorityQueue
<
int
[]>
pq
=
new
PriorityQueue
<>((
a
,
b
) ->
b
[
0
] -
a
[
0
]);
for
(
int
i
=
0
;
i
<
26
; ++
i
) {
if
(
cnt
[
i
] >
0
) {
pq
.
offer
(
new
int
[] {
cnt
[
i
],
i
});
}
}
Deque
<
int
[]>
q
=
new
ArrayDeque
<>();
StringBuilder
ans
=
new
StringBuilder
();
while
(!
pq
.
isEmpty
()) {
var
p
=
pq
.
poll
();
int
v
=
p
[
0
],
c
=
p
[
1
];
ans
.
append
((
char
) (
'a'
+
c
));
q
.
offer
(
new
int
[] {
v
-
1
,
c
});
if
(
q
.
size
() >=
k
) {
p
=
q
.
pollFirst
();
if
(
p
[
0
] >
0
) {
pq
.
offer
(
p
);
}
}
}
return
ans
.
length
() ==
n
?
ans
.
toString
() :
""
;
}
}
Back
|
FazBrowse Home
|
New Git URL