Get into the habit of writing together! This is the 7th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .
Topic description
This is 796. Rotate Strings on LeetCode on an Easy difficulty .
Tag : "simulation"
Given two strings, s
and goal
. If after several spin operations, s
it can become goal
, then return true
.
s
The rotation operation is to move s
the leftmost character to the rightmost.
- For example, if
s = 'abcde'
, after one rotation the result is'bcdea'
.
Example 1:
输入: s = "abcde", goal = "cdeab"
输出: true
复制代码
Example 2:
输入: s = "abcde", goal = "abced"
输出: false
复制代码
hint:
s
andgoal
consists of lowercase English letters
simulation
Since each rotation operation is to move the leftmost character to the rightmost, if goal
can be obtained s
through multiple steps of rotation, then goal
must appear in s + s
, that is, it is satisfied (s + s).contains(goal)
, and at the same time, for the result caused by s
itself too long, we need to First make sure that the two strings are of equal length.
Code:
class Solution {
public boolean rotateString(String s, String goal) {
return s.length() == goal.length() && (s + s).contains(goal);
}
}
复制代码
- time complexity:
- Space complexity:
finally
This is the first No.796
article series starts on 2021/01/01. As of the starting date, there are 1916 questions on LeetCode, some of which are locked. We will first put all the questions without locks. Topic finished.
In this series of articles, in addition to explaining the problem-solving ideas, the most concise code will be given as much as possible. If general solutions are involved, corresponding code templates will also be provided.
In order to facilitate students to debug and submit code on the computer, I have established a related repository: github.com/SharingSour… .
In the warehouse address, you can see the link to the solution of the series of articles, the corresponding code of the series of articles, the link to the original question of LeetCode and other preferred solutions.