43 左旋转字符串
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。
示例:
输入: "abcXYZdef", 3
输出: "XYZdefabc"解题思路
核心思想:字符串切片。
关键步骤:
- 如果n大于字符串长度,取模
- 切片重组:s[n:] + s[:n]
时间复杂度:O(n) 空间复杂度:O(n)
Python 实现
python
def left_rotate_string(s, n):
"""
左旋转字符串
Args:
s: 字符串
n: 旋转位数
Returns:
str: 旋转后的字符串
"""
if not s:
return ""
n = n % len(s)
return s[n:] + s[:n]
# 测试代码
if __name__ == "__main__":
test_cases = [
("abcXYZdef", 3),
("abcdefg", 2),
("", 3),
("a", 1),
("abcdefg", 10),
]
for s, n in test_cases:
print(f"'{s}'左旋{n}位 → '{left_rotate_string(s, n)}'")
# 输出:
# 'abcXYZdef'左旋3位 → 'XYZdefabc'
# 'abcdefg'左旋2位 → 'cdefgab'
# ''左旋3位 → ''
# 'a'左旋1位 → 'a'
# 'abcdefg'左旋10位 → 'cdefgab'图解
示例: "abcXYZdef", n=3
s[:3] = "abc"
s[3:] = "XYZdef"
结果: "XYZdef" + "abc" = "XYZdefabc"
---
示例: "abcdefg", n=10
n % len(s) = 10 % 7 = 3
s[:3] = "abc"
s[3:] = "defg"
结果: "defg" + "abc" = "defgabc"