Input: s ="aabb"Output: 2Explanation:
We can obtain two palindromes from s,"abba" and "baab".- We can obtain "abba" from s in2 moves:"a _**ab**_ b"->"ab _**ab**_ "->"abba".- We can obtain "baab" from s in2 moves:"a _**ab**_ b"->"_**ab**_ ab"->"baab".Thus, the minimum number of moves needed to make s a palindrome is2.
Input: s ="letelt"Output: 2Explanation:
One of the palindromes we can obtain from s in2 moves is"lettel".One of the ways we can obtain it is"lete _**lt**_ "->"let _**et**_ l"->"lettel".Other palindromes such as "tleelt" can also be obtained in2 moves.It can be shown that it is not possible to obtain a palindrome in less than 2 moves.
To make a palindrome, match characters from both ends. If the left and right match, move inward. If not, find the matching character for the left (or right) and swap it adjacent until it reaches the correct position, counting moves. If a character is unique (odd count), it must be in the center.
Else, search for a matching character for s[left] from right-1 to left+1. If found, swap it rightward, counting moves. If not found, swap s[left] to the center, counting moves.
classSolution {
funminMovesToMakePalindrome(s: String): Int {
val arr = s.toCharArray()
var ans = 0; var l = 0; var r = arr.size - 1while (l < r) {
if (arr[l] == arr[r]) {
l++; r-- } else {
var k = r
while (k > l && arr[k] != arr[l]) k--if (k == l) {
arr[l] = arr[l+1].also { arr[l+1] = arr[l] }
ans++ } else {
for (i in k until r) {
arr[i] = arr[i+1].also { arr[i+1] = arr[i] }
ans++ }
l++; r-- }
}
}
return ans
}
}
classSolution:
defminMovesToMakePalindrome(self, s: str) -> int:
arr = list(s)
ans, l, r =0, 0, len(arr) -1while l < r:
if arr[l] == arr[r]:
l +=1; r -=1else:
k = r
while k > l and arr[k] != arr[l]:
k -=1if k == l:
arr[l], arr[l+1] = arr[l+1], arr[l]
ans +=1else:
for i in range(k, r):
arr[i], arr[i+1] = arr[i+1], arr[i]
ans +=1 l +=1; r -=1return ans
impl Solution {
pubfnmin_moves_to_make_palindrome(s: String) -> i32 {
letmut arr: Vec<char>= s.chars().collect();
letmut ans =0;
let (mut l, mut r) = (0, arr.len() -1);
while l < r {
if arr[l] == arr[r] {
l +=1; r -=1;
} else {
letmut k = r;
while k > l && arr[k] != arr[l] { k -=1; }
if k == l {
arr.swap(l, l+1);
ans +=1;
} else {
for i in k..r {
arr.swap(i, i+1);
ans +=1;
}
l +=1; r -=1;
}
}
}
ans
}
}