Rotate String
XXX.Rotate String
String
Simulation
Problem Statement:
Given two strings s
and goal
, return true
if and only if goal
is a rotation of s
. A rotation means we can rearrange the characters of s
by moving some number of characters from the start to the end, keeping their relative order.
Algorithm:
- Check if the lengths of
s
andgoal
are different. If so, returnfalse
. - Concatenate
s
with itself to create a doubled string. - Check if
goal
is a substring of the doubled string using thecontains
function or equivalent.
Complexity:
Time: O(n), where n
is the length of s
| Space: O(n) for creating the concatenated string.
Java Implementation:
public boolean rotateString(String s, String goal) {
// Check if the lengths are different
if (s.length() != goal.length()) return false;
// Concatenate 's' with itself
String doubledString = s + s;
// Check if 'goal' is a substring of the doubled string
return doubledString.contains(goal);
}
Python Implementation:
def rotateString(s, goal):
# Check if lengths are different
if len(s) != len(goal):
return False
# Concatenate s with itself and check if goal is a substring
return goal in (s + s)
C++ Implementation:
bool rotateString(string s, string goal) {
// Check if lengths are different
if (s.length() != goal.length()) return false;
// Concatenate s with itself and check if goal is a substring
return (s + s).find(goal) != string::npos;
}