leetcode 796. 旋转字符串 简单

给定两个字符串, 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 由小写英文字母组成

分析:将 s 自己复制一遍,放到 s 的末尾,即用一个新的字符串 ss=s+s 代替旋转操作。遍历字符串 ss,从第 i 到第 i+len 位就是旋转了 i 次后的字符串,每次取字串进行对比即可。

cpp 复制代码
class Solution {
public:
    bool rotateString(string s, string goal) {
        int len=s.size(),l=goal.size();
        if(len!=l)return false;

        string ss=s+s;
        for(int i=0;i<len;++i)
            if(ss.substr(i,len)==goal)return true;
        return false;
    }
};
相关推荐
Nil2081 天前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil2082 天前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_674571972 天前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂2 天前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin7702 天前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao2 天前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1232 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi2 天前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z3 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2083 天前
leetcode 64最小路径和
算法·leetcode·职场和发展