Minimum Adjacent Swaps to Make Palindrome
Given a string, what is the minimum number of adjacent swaps required to convert a string into a palindrome. If not possible, return -1
.
Example 1:
Input: mamad
Output: 3
Explanation:
swap m
with a
=> maamd
swap m
with d
=> maadm
swap a
with d
=> madam
Example 2:
Input: asflkj
Output: -1
Example 3:
Input: mideld
Output: 3
Explanation:
swap e
with l
=> midled
swap e
with d
=> midlde
swap l
with d
=> middle
Try it yourself
Implementation
1 | 1 |
| |
2 | 2 |
| |
3 | - |
| |
3 | + |
| |
4 | + |
| |
5 | + | ||
6 | + |
| |
7 | + |
| |
8 | + |
| |
9 | + |
| |
10 | + | ||
11 | + |
| |
12 | + |
| |
13 | + |
| |
14 | + |
| |
15 | + |
| |
16 | + | ||
17 | + |
| |
18 | + |
| |
19 | + |
| |
20 | + |
| |
21 | + |
| |
22 | + |
| |
23 | + |
| |
24 | + |
| |
4 | 25 |
| |
5 | 26 |
| |
6 | 27 |
| |
7 | 28 |
|
Loading full content...