数据结构【字符串】| leetcode 796. 旋转字符串(简单)

该博客讨论了两种方法解决字符串旋转问题:一是通过模拟旋转过程并比较字符,二是利用子字符串搜索。第一种方法的时间复杂度为O(n^2),而第二种方法通过检查目标字符串是否为原字符串扩展后的子串,时间复杂度降低到O(n)。这两种方法在空间复杂度上均为O(1)或O(n)。
摘要由CSDN通过智能技术生成

代码链接:https://leetcode.cn/problems/rotate-string/solution/xuan-zhuan-zi-fu-chuan-by-leetcode-solut-4hlp/

方法一:模拟

思路

首先,如果 s s s g o a l goal goal 的长度不一样,那么无论怎么旋转, s s s 都不能得到 g o a l goal goal,返回 f a l s e false false。在长度一样(都为 n n n)的前提下,假设 s s s 旋转 i i i 位,则与 g o a l goal goal 中的某一位字符 g o a l [ j ] goal[j] goal[j] 对应的原 s s s 中的字符应该为 s [ ( i + j )   m o d   n ] s[(i+j) \bmod n] s[(i+j)modn]。在固定 i i i 的情况下,遍历所有 j j j,若对应字符都相同,则返回 t r u e true true。否则,继续遍历其他候选的 i i i。若所有的 i i i 都不能使 s s s 变成 g o a l goal goal,则返回 f a l s e false false

代码

class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        m, n = len(s), len(goal)
        if m != n:
            return False
        for i in range(n):
            for j in range(n):
                if s[(i + j) % n] != goal[j]:
                    break
            else:
                return True
        return False

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2),其中 n n n 是字符串 s s s 的长度。我们需要双重循环来判断。
  • 空间复杂度: O ( 1 ) O(1) O(1)。仅使用常数空间。

方法二:搜索子字符串

思路

首先,如果 s s s g o a l goal goal 的长度不一样,那么无论怎么旋转, s s s 都不能得到 g o a l goal goal,返回 f a l s e false false。字符串 s + s s+s s+s 包含了所有 s s s 可以通过旋转操作得到的字符串,只需要检查 g o a l goal goal 是否为 s + s s+s s+s 的子字符串即可。本题解中采用直接调用库函数in的方法。

代码

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

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n 是字符串 s s s 的长度。 K M P KMP KMP 算法搜索子字符串的时间复杂度为 O ( n ) O(n) O(n),其他搜索子字符串的方法会略有差异。
  • 空间复杂度: O ( n ) O(n) O(n),其中 n n n 是字符串 s s s 的长度。 K M P KMP KMP 算法搜索子字符串的空间复杂度为 O ( n ) O(n) O(n),其他搜索子字符串的方法会略有差异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值