1
0
mirror of https://gitee.com/coder-xiaomo/leetcode-problemset synced 2025-01-10 18:48:13 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
leetcode-problemset/leetcode-cn/problem (English)/得到回文串的最少操作次数(English) [minimum-number-of-moves-to-make-palindrome].html

42 lines
1.9 KiB
HTML

<p>You are given a string <code>s</code> consisting only of lowercase English letters.</p>
<p>In one <strong>move</strong>, you can select any two <strong>adjacent</strong> characters of <code>s</code> and swap them.</p>
<p>Return <em>the <strong>minimum number of moves</strong> needed to make</em> <code>s</code> <em>a palindrome</em>.</p>
<p><strong>Note</strong> that the input will be generated such that <code>s</code> can always be converted to a palindrome.</p>
<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = &quot;aabb&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong>
We can obtain two palindromes from s, &quot;abba&quot; and &quot;baab&quot;.
- We can obtain &quot;abba&quot; from s in 2 moves: &quot;a<u><strong>ab</strong></u>b&quot; -&gt; &quot;ab<u><strong>ab</strong></u>&quot; -&gt; &quot;abba&quot;.
- We can obtain &quot;baab&quot; from s in 2 moves: &quot;a<u><strong>ab</strong></u>b&quot; -&gt; &quot;<u><strong>ab</strong></u>ab&quot; -&gt; &quot;baab&quot;.
Thus, the minimum number of moves needed to make s a palindrome is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = &quot;letelt&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong>
One of the palindromes we can obtain from s in 2 moves is &quot;lettel&quot;.
One of the ways we can obtain it is &quot;lete<u><strong>lt</strong></u>&quot; -&gt; &quot;let<u><strong>et</strong></u>l&quot; -&gt; &quot;lettel&quot;.
Other palindromes such as &quot;tleelt&quot; can also be obtained in 2 moves.
It can be shown that it is not possible to obtain a palindrome in less than 2 moves.
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 &lt;= s.length &lt;= 2000</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
<li><code>s</code> can be converted to a palindrome using a finite number of moves.</li>
</ul>