We call a string s of even length n an anti-palindrome if for each index 0 <= i < n, s[i] != s[n - i - 1].
Given a string s, your task is to make s an anti-palindrome by doing
any number of operations (including zero).
In one operation, you can select two characters from s and swap them.
Return the resulting string. If multiple strings meet the conditions, return the lexicographically smallest one. If it can’t be made into an anti-palindrome, return "-1".
Input: s ="abca"Output: "aabc"Explanation:
`"aabc"`is an anti-palindrome string since `s[0] != s[3]` and `s[1] != s[2]`.Also, it is a rearrangement of `"abca"`.
Example 2:
1
2
3
4
5
Input: s ="abba"Output: "aabb"Explanation:
`"aabb"`is an anti-palindrome string since `s[0] != s[3]` and `s[1] != s[2]`.Also, it is a rearrangement of `"abba"`.
Example 3:
1
2
3
4
5
6
Input: s ="cccd"Output: "-1"Explanation:
You can see that no matter how you rearrange the characters of `"cccd"`,either `s[0] == s[3]` or `s[1] == s[2]`. So it can not form an anti-palindrome
string.
To make a string anti-palindrome, for each index i, we need s[i] != s[n-i-1]. The main challenge is to rearrange the string so that no character is mirrored. If any character appears more than n/2 times, it’s impossible. Otherwise, we can sort the string and use two pointers to assign characters to the first and second halves, ensuring no mirrored pair is equal. For lexicographical minimality, we use the smallest available characters for the left half.
classSolution {
funmakeAntiPalindrome(s: String): String {
val n = s.length
val cnt = IntArray(26)
for (c in s) cnt[c-'a']++if (cnt.any { it > n/2 }) return"-1"val arr = s.toCharArray().sorted().toCharArray()
val left = arr.sliceArray(0 until n/2)
val right = arr.sliceArray(n/2 until n)
val ans = CharArray(n)
for (i in0 until n/2) {
ans[i] = left[i]
ans[n-i-1] = right[i]
}
for (i in0 until n/2) {
if (ans[i] == ans[n-i-1]) {
var j = i+1while (j < n/2&& (ans[j] == ans[n-i-1] || ans[i] == ans[n-j-1])) j++if (j == n/2) return"-1"val tmp = ans[i]; ans[i] = ans[j]; ans[j] = tmp
}
}
return String(ans)
}
}
classSolution:
defmakeAntiPalindrome(self, s: str) -> str:
n = len(s)
from collections import Counter
cnt = Counter(s)
if any(v > n//2for v in cnt.values()):
return"-1" arr = sorted(s)
left = arr[:n//2]
right = arr[n//2:]
ans = [''] * n
for i in range(n//2):
ans[i] = left[i]
ans[n-i-1] = right[i]
for i in range(n//2):
if ans[i] == ans[n-i-1]:
j = i+1while j < n//2and (ans[j] == ans[n-i-1] or ans[i] == ans[n-j-1]):
j +=1if j == n//2:
return"-1" ans[i], ans[j] = ans[j], ans[i]
return''.join(ans)