LeetCode 题解工作台
旋转字符串
给定两个字符串, s 和 goal 。如果在若干次旋转操作之后, s 能变成 goal ,那么返回 true 。 s 的 旋转操作 就是将 s 最左边的字符移动到最右边。 例如, 若 s = 'abcde' ,在旋转一次之后结果就是 'bcdea' 。 示例 1: 输入: s = "abcde", …
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · string·结合·string·matching
答案摘要
class Solution: def rotateString(self, s: str, goal: str) -> bool:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·string·matching 题型思路
题目描述
给定两个字符串, s 和 goal。如果在若干次旋转操作之后,s 能变成 goal ,那么返回 true 。
s 的 旋转操作 就是将 s 最左边的字符移动到最右边。
- 例如, 若
s = 'abcde',在旋转一次之后结果就是'bcdea'。
示例 1:
输入: s = "abcde", goal = "cdeab" 输出: true
示例 2:
输入: s = "abcde", goal = "abced" 输出: false
提示:
1 <= s.length, goal.length <= 100s和goal由小写英文字母组成
解题思路
方法一
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
return len(s) == len(goal) and goal in s + s
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) due to concatenation and single substring search. Space complexity is O(n) to store the doubled string. Edge cases like identical strings or single-character strings do not change this bound. |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Look for recognition that concatenating s with itself captures all rotations.
- question_mark
Check if candidate handles edge cases like empty strings or single-character strings.
- question_mark
Watch for inefficient nested loops that simulate every shift explicitly.
常见陷阱
外企场景- error
Simulating each rotation with loops instead of concatenation causes unnecessary O(n^2) time.
- error
Forgetting to compare lengths before processing leads to false positives.
- error
Assuming only one shift is required instead of considering all rotations.
进阶变体
外企场景- arrow_right_alt
Check rotations allowing both left and right shifts to extend the basic pattern.
- arrow_right_alt
Find the minimal number of shifts needed to reach the goal string.
- arrow_right_alt
Apply the string plus string matching pattern to circular arrays or lists instead of strings.