n = len(s) # 因為題目確保給定的 s 也是回文,所以只需要統計前半段的字元數量即可 cnt = Counter(s[: n // 2]) mid = s[n // 2] if n & 1else""
m = n // 2
perm = fact[m] for val in cnt.values(): perm //= fact[val]
if perm < k: return""
defupdate(ch: str, delta: int): nonlocal perm, m # 直接依 m 與 cnt[ch] 變化增量更新,先乘後除保證整除 if delta == 1: m += 1 cnt[ch] += 1 perm = perm * m // cnt[ch] else: perm = perm * cnt[ch] // m m -= 1 cnt[ch] -= 1
ans = [] for _ inrange(m): for ch in ascii_lowercase: if cnt[ch] == 0: continue update(ch, -1) if k <= perm: ans.append(ch) break k -= perm update(ch, 1)
classSolution: defsmallestPalindrome(self, s: str, k: int) -> str: n = len(s) # 因為題目確保給定的 s 也是回文,所以只需要統計前半段的字元數量即可 cnt = Counter(s[: n // 2]) mid = s[n // 2] if n & 1else""
m = n // 2
defperm(n: int) -> int: # C(n, c1) * C(n - c1, c2) * ... * C(n - c1 - c2 - ... - c(n-1), cn) res = 1 for c in cnt.values(): if c == 0: continue # 用避免溢出的方式逐步計算 C(n, c) m = min(c, n - c) # C(n, m) = C(n, n - m) for i inrange(1, m + 1): res = res * (n + 1 - i) // i if res >= k: # 若 res >= k,則直接回傳 k,避免溢出 return k n -= c return res
if perm(m) < k: return""
ans = [] for i inrange(m): for ch in ascii_lowercase: if cnt[ch] == 0: continue cnt[ch] -= 1 p = perm(m - i - 1) if k <= p: ans.append(ch) break k -= p cnt[ch] += 1
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.