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--) { if(s[i] == s[f]) break; } if(f == i) { res += s.length() / 2 - i; j++; } else { res += j - f; for(; f < j; f++) { swap(s[f], s[f+1]); } } } return res; } };
|