Repository navigation
Expand file tree
/
Copy pathlc3518.java
More file actions
78 lines (63 loc) · 1.82 KB
/
Copy pathlc3518.java
File metadata and controls
78 lines (63 loc) · 1.82 KB
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
public class lc3518 {
class Solution {
private long comb(long n, long m, long k) {
long res = 1;
m = Math.min(m, n - m);
for (long i = 1; i <= m; i++) {
res = (res * (n - i + 1)) / i;
if (res > k) {
return k + 1;
}
}
return res;
}
private long permutations(int rem, int[] bucket, long k) {
long ways = 1;
for (int i = 0; i < 26; i++) {
if (bucket[i] == 0) {
continue;
}
ways *= comb(rem, bucket[i], k);
if (ways > k) {
break;
}
rem -= bucket[i];
}
return ways;
}
public String smallestPalindrome(String s, long k) {
int partition = s.length() / 2;
int[] bucket = new int[26];
for (int i = 0; i < partition; i++) {
bucket[s.charAt(i) - 97] += 1;
}
StringBuilder left = new StringBuilder();
long startIndex = 1;
for (int pos = 0; pos < partition; pos++) {
for (int i = 0; i < 26; i++) {
if (bucket[i] == 0) {
continue;
}
bucket[i] -= 1;
long ways = permutations(partition - pos - 1, bucket, k);
if (startIndex + ways > k) {
left.append((char) (i + 97));
break;
}
bucket[i] += 1;
startIndex += ways;
}
}
if (left.length() < partition) {
return "";
}
if (s.length() % 2 != 0) {
left.append(s.charAt(partition));
}
for (int i = partition - 1; i >= 0; i--) {
left.append(left.charAt(i));
}
return left.toString();
}
}
}