🔗 🟡 3517. Smallest Palindromic Rearrangement I

Problem Statement

題目簡述

給定一個回文字串 ss,請回傳 ss 的所有回文排列中字典序最小的字串。

Constraints

約束條件

  • 1≤∣s∣≤1051 \le |s| \le 10^5
  • ss 僅包含小寫英文字母
  • 保證 ss 本身是回文字串

思路:貪心 + 計數排序

任意回文字串都可以拆成三部分:前半段、正中間字元(僅當長度 nn 為奇數時存在),以及前半段的反轉。其中正中間字元固定是唯一出現奇數次的字元,而後半段由前半段唯一決定。

關鍵觀察

要讓整個回文字串字典序最小,等價於讓前半段字典序最小。由 貪心(Greedy) 策略,只需把前半段的所有字元依字母序 'a' 到 'z' 由小到大排列即可。

由於字元集只有 ∣Σ∣=26|\Sigma| = 26 種小寫英文字母,直接統計各字母頻率並依序重建前半段,即為線性時間的 計數排序(Counting Sort)。

方法一:統計整個字串

統計整個字串 ss 中每個字母的出現次數 cnt[c]\textit{cnt}[c]:

  • 若 cnt[c]\textit{cnt}[c] 為奇數,該字母就是正中間字元 mid\textit{mid};
  • 無論奇偶,該字母在前半段各貢獻 ⌊cnt[c]/2⌋\lfloor \textit{cnt}[c] / 2 \rfloor 個。

依 'a' 到 'z' 串接得到前半段 ans\textit{ans},最後回傳 ans+mid+ansrev\textit{ans} + \textit{mid} + \textit{ans}^{\text{rev}}。

複雜度分析

  • 時間複雜度:O(n+∣Σ∣)\mathcal{O}(n + |\Sigma|),其中 n=∣s∣n = |s|,∣Σ∣=26|\Sigma| = 26。
  • 空間複雜度:O(n+∣Σ∣)\mathcal{O}(n + |\Sigma|),用於字元計數陣列與構造結果字串(不計輸出為 O(∣Σ∣)\mathcal{O}(|\Sigma|))。

方法二:僅統計前半段

題目保證輸入 ss 本身已經是回文字串,因此:

  • 前半段 s[:n // 2] 內各字母的出現次數,天然就是整串出現次數的一半;
  • 當 nn 為奇數時,正中間的字元必然就是 s[n // 2]。

因此只需對前半段做計數排序即可直接組出 ans\textit{ans},省去掃描後半段與除以 22 的步驟。

複雜度分析

  • 時間複雜度:O(n+∣Σ∣)\mathcal{O}(n + |\Sigma|),其中 n=∣s∣n = |s|,∣Σ∣=26|\Sigma| = 26(常數比方法一更小)。
  • 空間複雜度:O(n+∣Σ∣)\mathcal{O}(n + |\Sigma|),用於切片前半段、字元計數陣列與構造結果字串。

Code

方法一:統計整個字串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def smallestPalindrome(self, s: str) -> str:
cnt = [0] * 26
for ch in s:
cnt[ord(ch) - ord("a")] += 1

ans = []
mid = ""
for c, val in enumerate(cnt):
if val & 1:
mid = chr(c + ord("a"))
ans.append(chr(c + ord("a")) * (val // 2))
ans = "".join(ans)
return ans + mid + ans[::-1]

方法二:僅統計前半段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def smallestPalindrome(self, s: str) -> str:
n = len(s)

# 因為題目確保給定的 s 也是回文,所以只需要統計前半段的字元數量即可
cnt = [0] * 26
for ch in s[: n // 2]:
cnt[ord(ch) - ord("a")] += 1

ans = []
for c, val in enumerate(cnt):
ans.append(chr(c + ord("a")) * val)

ans = "".join(ans)
mid = s[n // 2] if n & 1 else ""
return ans + mid + ans[::-1]

寫在最後

Cover Image Credit

The cover image was created by @柊栞zhongkan. All rights belong to the original artist.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.