Intuition
A rotation of s is just s[k:] + s[:k] for some k. There are at most n distinct rotations, so we can try them all and check if any equals goal.
Explanation
Approach
- If lengths differ, return
Falseimmediately. - For each
kfrom0ton - 1, builds[k:] + s[:k]and compare withgoal. - If any rotation matches, return
True. OtherwiseFalse.
Complexity
- Time:
O(n²)—nrotations, each compared inO(n). - Space:
O(n)— temporary rotated string.
Implementation
import java.util.*;
class Solution {
public boolean rotateString(String s, String goal) {
if (s.length() != goal.length()) return false;
for (int k = 0; k < s.length(); k++) {
if ((s.substring(k) + s.substring(0, k)).equals(goal)) return true;
}
return false;
}
}