檢查字串的任何一個anagram是否是迴文(Python)


假設我們有一個字串 s。我們必須檢查該字串的 anagram 是否構成迴文。

因此,如果輸入類似於 s = "aarcrec",則輸出將為 True,因為該字串的一個 anagram 是 "racecar",它是迴文。

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

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

讓我們看看下面的實現,以便更好地理解:

示例

 線上演示

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

輸入

"aarcrec"

輸出

True

更新於:2020-12-30

353 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告