Rotate String
Problem
Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
s = "abcde", goal = "cdeab"truedef rotateString(s, goal):
return len(s) == len(goal) and goal in s + s
var rotateString = function(s, goal) {
return s.length === goal.length && (s + s).includes(goal);
};
class Solution {
public boolean rotateString(String s, String goal) {
return s.length() == goal.length() && (s + s).contains(goal);
}
}
class Solution {
public:
bool rotateString(string s, string goal) {
return s.size() == goal.size() && (s + s).find(goal) != string::npos;
}
};
Explanation
There is a beautiful one-line trick here: goal is a rotation of s if and only if it shows up inside s + s (the string glued to itself), as long as both strings are the same length.
Why does that work? Every possible rotation of s is just a chunk you read off by starting at some index and wrapping around to the front. Concatenating s with itself lays out all of those wrap-around chunks as ordinary contiguous substrings, so a single substring search finds any rotation.
The length check s.length == goal.length matters too: without it, a shorter goal could accidentally appear inside s + s even though it isn't a true rotation.
Example: s = "abcde", goal = "cdeab". Then s + s = "abcdeabcde", and "cdeab" appears starting at index 2. Lengths match and the substring is found, so the answer is true.
The code reduces to s.length == goal.length and goal in s + s, leaning on the built-in substring search to do the heavy lifting.