Make writing a habit together! This is the 7th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
Topic describes
This is 796 on LeetCode. Rotate string, easy difficulty.
Tag: “Simulation”
Given two strings, S and goal. Returns true if s can become goal after a number of rotation operations.
The rotation operation of S moves the leftmost character of S to the right.
- For example, if the
s = 'abcde'
After one rotation, the result is going to be'bcdea'
。
Example 1:
Input: s = "abcde", goal = "cdeab" Output: trueCopy the code
Example 2:
Input: s = "abcde", goal = "abced" Output: falseCopy the code
Tip:
s
和goal
Consists of lowercase English letters
simulation
Because each rotation operation moves the leftmost character to the right, if GOAL can be derived from S through multiple steps of rotation, then goal must appear in S + S, which satisfies (S + S). Contains (goal). At the same time, in order to hold the result caused by s itself being too long, We need to make sure that the two strings are the same length.
Code:
class Solution {
public boolean rotateString(String s, String goal) {
returns.length() == goal.length() && (s + s).contains(goal); }}Copy the code
- Time complexity: O(n)O(n)O(n)
- Space complexity: O(n)O(n)O(n)
The last
This is the No.796 of our “Brush through LeetCode” series, which started on 2021/01/01. There are 1916 topics on LeetCode as of the start date, some of which have locks.
In this series of articles, in addition to explaining how to solve the problem, I will also present the most concise code possible. If a general solution is involved, the corresponding code template will also be used.
In order to facilitate the students to debug and submit the code on the computer, I set up the relevant warehouse: github.com/SharingSour… .
In the repository, you’ll see links to the series of articles, the corresponding code for the series of articles, the LeetCode source links, and other preferred solutions.