Leetcode Problem 796: Rotate String
Given two strings s and goal, return True if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position. For example, if s = 'abcde', then it will be 'bcdea' after one shift.
Example 1:
s = "abcde", goal = "cdeab"trueExample 2:
s = "abcde", goal = "abced"falses and goal?s or goal is empty?s and goal are different. If they are, return False because a string cannot be rotated into another string of a different length.s with itself (i.e., s + s). This will include all possible rotations of s as substrings.goal is a substring of the concatenated string s + s.s.goal is a substring of s + s will take (O(n)) on average assuming efficient substring search algorithms.So, the overall time complexity is (O(n)).
def rotateString(s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
concatenated_s = s + s
return goal in concatenated_s
Here is how the solution works:
s and goal are the same.s with itself to form a new string concatenated_s.goal is a substring of concatenated_s, and returns True if it is, otherwise False.This method ensures an efficient check for all rotations of s within a linear time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?