1
A
回答
2
遞歸你知道你的函數適用於:
- 基本情況)一個空字符串,必須返回一個空字符串;
- rec case)以
b
開頭的字符串必須用a
替換b
並檢查字符串的其餘部分; - REC情況下)否則,返回鏈接到該字符串的其餘部分字符串的第一個字符返回遞歸
這裏的算法:
def rec_replace(string, a, b):
if not string: #if the string is empty
return ""
elif string[:len(b)] == b: #if the string start with b, replace it with a
return a + rec_replace(string[len(b):], a, b)
else: #else, add this character and go to the next one
return string[0] + rec_replace(string[1:], a, b)
測試:
print rec_replace("hello this is hello a simple hello test", "ok", "hello")
輸出:
ok this is ok a simple ok test
相關問題
- 1. 替換字符串用另一個子
- 2. 用一個StringBuffer子字符串替換一個子字符串
- 3. 替換字符串中出現的第n個子字符串
- 4. 替換字符串的子字符串用另一個字符串
- 5. 在一個很長的字符串替換字符串的所有出現的另一個子
- 6. Java:用一個字符串替換所有匹配的字符串子串
- 7. 用包含原始子字符串的條件子字符串替換多個出現的子字符串
- 8. 使用遞歸替換另一個字符串的部分(Java)
- 9. 替換字符串中最後出現的子字符串
- 10. 替換所有出現的字符串
- 11. 替換所有的字符串出現
- 12. 替換字符串中的所有子字符串c#
- 13. 替換所有子字符串中
- 14. 用另一個字符串替換字符串中的字符?
- 15. 如何替換kotlin中所有出現的子字符串
- 16. 使用遞歸生成給定字符串的所有子字符串
- 17. 使用PHP替換遞歸字符串
- 18. 用SQL存儲過程中的字符串中的另一個子字符串替換特定子字符串
- 19. 刪除字符串中所有子字符串的出現
- 20. 字符串中出現的所有子字符串
- 21. PHP查找字符串中出現的所有子字符串
- 22. 獲取字符串中所有子字符串的出現
- 23. 查找字符串中出現的所有子字符串
- 24. 字符串解析 - 用一個唯一的替換替換每個重複出現的子字符串
- 25. 是字符串集所有子字符串的另一組
- 26. 用另一個詞或句子替換字符串中的字
- 27. Java僅替換字符串中第一次出現的子串
- 28. 用另一個字符串替換子串rails
- 29. 用文本流替換所有出現的一個字符串
- 30. 使用指向字符串的指針數組替換字符串中的另一個子字符串
遞歸在什麼意義上? –
告訴我們你的代碼? –