LeetCode 题解工作台

旋转字符串

给定两个字符串, s 和 goal 。如果在若干次旋转操作之后, s 能变成 goal ,那么返回 true 。 s 的 旋转操作 就是将 s 最左边的字符移动到最右边。 例如, 若 s = 'abcde' ,在旋转一次之后结果就是 'bcdea' 。 示例 1: 输入: s = "abcde", …

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · string·结合·string·matching

bolt

答案摘要

class Solution: def rotateString(self, s: str, goal: str) -> bool:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 string·结合·string·matching 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定两个字符串, 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 <= 100
  • s 和 goal 由小写英文字母组成
lightbulb

解题思路

方法一

1
2
3
4
class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        return len(s) == len(goal) and goal in s + s
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

旋转字符串题解:string·结合·string·matchi… | LeetCode #796 简单