檢查給定字串的字元是否可以重新排列成迴文 (Python)


假設我們有一個字串 s,我們需要檢查給定字串的字元是否可以重新排列成迴文。

因此,如果輸入類似於 s = "raaecrc",則輸出為 True,因為我們可以將其重新排列為 "racecar",這是一個迴文。

為了解決這個問題,我們將遵循以下步驟:

  • freq := 一個對映,用於儲存 s 中所有字元及其頻率
  • odd_count := 0
  • 對於 freq 所有值的列表中的每個元素 i:
    • 如果 i 是奇數,則
      • odd_count := odd_count + 1
    • 如果 odd_count > 1,則
      • 返回 False
  • 返回 True

讓我們看看下面的實現來更好地理解:

示例

 線上演示

from collections import defaultdict
def solve(st) :
   freq = defaultdict(int)
   for char in st :
      freq[char] += 1
   odd_count = 0
   for i in freq.values():
      if i % 2 == 1:
         odd_count = odd_count + 1
      if odd_count > 1:
         return False
   return True
s = "raaecrc"
print(solve(s))

輸入

"raaecrc"

輸出

True

更新於:2020-12-30

1K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.