796. Rotating Strings: Simple Simulation Questions

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  sthe 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:

  • 1 < = s . l e n g t h , g o a l . l e n g t h < = 100 1 <= s.length, goal.length <= 100
  • s and  goal consists of lowercase English letters

simulation

Since each rotation operation is to move the leftmost character to the rightmost, if goalcan be obtained sthrough multiple steps of rotation, then goalmust appear in s + s, that is, it is satisfied (s + s).contains(goal), and at the same time, for the result caused by sitself 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: O ( n ) O(n)
  • Space complexity: O ( n ) O(n)

finally

This is the first No.796article 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.

Guess you like

Origin juejin.im/post/7083678407107543048