Leetcode 796: Rotate String
We are given two strings s
and goal
. We need to determine if s
can become goal
after a series of shifts. In one shift, s
is moved to the left by one position. For example, if s = "abcde"
, then it can be shifted to the left to become "bcdea"
, "cdeab"
, "deabc"
, "eabcd"
, and finally back to "abcde"
.
s
and goal
?
1 to 100
.s
to possibly be rotated into goal
, both strings need to be of the same length.To determine if s
can become goal
after a series of shifts:
s
with itself: This would allow us to check for any shifted versions within the new string.goal
is a substring within the concatenated string, then s
can be shifted to become goal
.public class Solution {
public boolean rotateString(String s, String goal) {
if (s.length() != goal.length()) {
return false;
}
String concatenated = s + s;
return concatenated.contains(goal);
}
}
s
and goal
have the same length. If not, return false
since they cannot be the same string after any number of shifts.s
with itself to create a new string. If goal
is a substring of this new string, it means that goal
can be formed by rotating s
.s
with itself takes O(n) time where n
is the length of s
.goal
is a substring in the concatenated string can be performed in O(n) time typically (char checking would take linear time given efficient implementations).Thus, the overall time complexity is O(n) where n
is the length of the strings s
and goal
.
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?