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
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
['elloh', 'llohe', 'lohel', 'ohell', 'hello']
广告