用 Python 编写一个程序,将一个长度为 n 的字符串向左旋转 n 次

pythonserver side programmingprogramming更新于 2025/12/23 13:32:17

假设我们有一个长度为 n 的字符串 s。我们必须通过将字符串旋转 1 位、2 位... n 位来找到所有旋转的字符串。

因此,如果输入为 s = "hello",则输出将是 ['elloh', 'llohe', 'lohel', 'ohell', 'hello']

为了解决这个问题,我们将遵循以下步骤 −

  • res := a new list
  • n := size of s
  • for i in range 0 to n, do
    • s := (s 的子字符串从索引 1 到 n-1) concatenate s[0]
    • 在末尾插入 s
  • 返回 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']

相关文章


有用资源