「每日LeetCode」2022年4月7日

本文最后更新于:2023年3月19日 晚上

796.旋转字符串

796.旋转字符串

Category Difficulty Likes Dislikes
algorithms Easy (54.77%) 219 -

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

Discussion | Solution

思路

如果可以通过旋转得到结果,那么两个原字符串首尾相接一定包含一个目标字符串。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* @lc app=leetcode.cn id=796 lang=javascript
*
* [796] 旋转字符串
*/

// @lc code=start
/**
* @param {string} s
* @param {string} goal
* @return {boolean}
*/
var rotateString = function (s, goal) {
return s.length === goal.length && (s + s).includes(goal);
};
// @lc code=end