Python 基礎知識簡單

遞歸刪除相鄰的重複項

「遞歸刪除相鄰重複項」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 remove_adjacent_duplicates(s) ,遞歸地從字串 s 中刪除所有相鄰的重複字符,直到沒有相鄰的重複字符為止。在每次傳遞中,刪除所有連續的相同字元對,然後對生成的字串重複該過程,直到其穩定。返回最終的字串。

約束條件
  • 0 <= len(s) <= 1000
  • s contains only lowercase English letters

範例

Example 1
Input
s = 'aabccba'
Output
'a'
Explanation

First pass: remove 'aa' and 'cc' -> 'bba'. Second pass: remove 'bb' -> 'a'. No more adjacent duplicates.

Example 2
Input
s = 'abcddcba'
Output
''
Explanation

Remove 'dd' -> 'abccba'. Remove 'cc' -> 'abba'. Remove 'bb' -> 'aa'. Remove 'aa' -> ''. Empty string.

Example 3
Input
s = 'abcd'
Output
'abcd'
Explanation

No adjacent duplicates exist, so the string remains unchanged.

Need a Hint?
考慮使用特定於遞歸的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。