-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
lc/3646/ #4637
lc/3646/
#4637
-
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
class Solution {
private static List pool = new ArrayList<>();
private static boolean inited = false;
public long specialPalindrome(long n) {
if (!inited) {
synchronized (Solution.class) {
if (!inited) {
initPool();
inited = true;
}
}
}
int idx = Collections.binarySearch(pool, n);
if (idx < 0) {
idx = -idx - 1;
} else {
idx++;
}
return pool.get(idx);
}
private void initPool() {
Consumer<String> addIfOk = s -> {
if (s.isEmpty() || s.length() >= 17) {
return;
}
try {
long value = Long.parseLong(s);
pool.add(value);
} catch (NumberFormatException e) {
}
};
BiConsumer<int[], Consumer<String>> gen = (cnt, adder) -> {
int totalLength = 0;
for (int d = 1; d <= 9; d++) {
totalLength += cnt[d];
}
if (totalLength == 0 || totalLength > 17) {
return;
}
int[] halfCnt = new int[10];
for (int d = 1; d <= 9; d++) {
halfCnt[d] = cnt[d] / 2;
}
final int halfLength;
{
int temp = 0;
for (int d = 1; d <= 9; d++) {
temp += halfCnt[d];
}
halfLength = temp;
}
final char mid;
{
char tempMid = 0;
for (int d = 1; d <= 9; d++) {
if ((cnt[d] & 1) == 1) {
tempMid = (char) ('0' + d);
break;
}
}
mid = tempMid;
}
StringBuilder half = new StringBuilder();
int[] hc = halfCnt.clone();
Runnable dfs = new Runnable() {
@Override
public void run() {
if (half.length() == halfLength) {
String reversed = new StringBuilder(half).reverse().toString();
String palindrome;
if (mid != 0) {
palindrome = half.toString() + mid + reversed;
} else {
palindrome = half.toString() + reversed;
}
adder.accept(palindrome);
return;
}
for (int d = 1; d <= 9; d++) {
if (hc[d] == 0) {
continue;
}
hc[d]--;
half.append((char) ('0' + d));
this.run();
half.deleteCharAt(half.length() - 1);
hc[d]++;
}
}
};
dfs.run();
};
int[] evenDigits = {2, 4, 6, 8};
int[] oddDigits = {1, 3, 5, 7, 9};
for (int mask = 1; mask < (1 << 4); mask++) {
int[] cnt = new int[10];
int totalLength = 0;
for (int i = 0; i < 4; i++) {
if ((mask & (1 << i)) != 0) {
int d = evenDigits[i];
cnt[d] = d;
totalLength += d;
}
}
if (totalLength <= 17) {
gen.accept(cnt, addIfOk);
}
}
for (int odd : oddDigits) {
for (int mask = 0; mask < (1 << 4); mask++) {
int[] cnt = new int[10];
int totalLength = odd;
cnt[odd] = odd;
for (int i = 0; i < 4; i++) {
if ((mask & (1 << i)) != 0) {
int d = evenDigits[i];
cnt[d] = d;
totalLength += d;
}
}
if (totalLength <= 17) {
gen.accept(cnt, addIfOk);
}
}
}
Collections.sort(pool);
List<Long> uniquePool = new ArrayList<>(new LinkedHashSet<>(pool));
pool.clear();
pool.addAll(uniquePool);
}
}
Beta Was this translation helpful? Give feedback.
All reactions
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment