[LeetCode] Minimum Number of Moves to Make Palindrome

2193. Minimum Number of Moves to Make Palindrome

You are given a string s consisting only of lowercase English letters.

In one move, you can select any two adjacent characters of s and swap them.

Return the minimum number of moves needed to make s a palindrome.

Note that the input will be generated such that s can always be converted to a palindrome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int minMovesToMakePalindrome(string s) {
int res = 0;
for(int i = 0, j = s.length() - 1; i < s.length() / 2; i++, j--) {
if(s[i] == s[j]) continue;
int f = j - 1;
for(; f >= i; f--) { //find closest character
if(s[i] == s[f]) break;
}
if(f == i) { //if closest character is at s[i], s[i] should move to middle of s
res += s.length() / 2 - i;
j++;
} else { //else, calculate distance and swap all nodes
res += j - f;
for(; f < j; f++) {
swap(s[f], s[f+1]);
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/06/PS/LeetCode/minimum-number-of-moves-to-make-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.