Python 中將大小為 n 的字串向左旋轉 n 次的程式
假設我們有一個大小為 n 的字串 s。我們要透過將它們旋轉 1 個位置、2 個位置……n 個位置來找到所有旋轉後的字串。
因此,如果輸入像 s = "hello",則輸出將是 ['elloh', 'llohe', 'lohel', 'ohell', 'hello']
為了解決這個問題,我們將遵循以下步驟 −
- res := 一個新列表
- n := s 的大小
- 對於 i 從 0 到 n,執行
- s := (s 從下標 1 到 n-1 的子字串) 拼接 s[0]
- 將 s 插入 res 的末尾
- 返回 res
示例
讓我們看看以下實現以獲得更好的理解 −
def solve(s): res = [] n = len(s) for i in range(0, n): s = s[1:n]+s[0] res.append(s) return res s = "hello" print(solve(s))
輸入
hello
輸出
['elloh', 'llohe', 'lohel', 'ohell', 'hello']
廣告