
Sponsored
Sponsored
In this approach, we use the property that a rotated version of a string s can be found as a substring of s + s. This is because rotating doesn't change the length of the string and by concatenating the string to itself, every possible rotation is covered.
Time Complexity: O(n^2), where n is the length of the string, due to using strstr.
Space Complexity: O(n), for the doubled string.
1class Solution {
2 public boolean rotateString(String s, String goal) {
3 if (s.length() != goal.length()) return false;
4 String doubled = s + s;
5 return doubled.contains(goal);
6 }
7}This Java solution follows the same logic by first checking the lengths of the two strings. If they match, it creates a new string by concatenating s with itself and checks if this newly formed string contains goal as a substring.
This approach simulates rotating the string s multiple times (equal to its length) to check if it equals goal at any point. This is a straightforward but less efficient method compared to the concatenation method.
Time Complexity: O(n^2), because we check for each possible rotation of s for a match with goal.
Space Complexity: O(1), as no additional storage is used beyond some counters.
1
The C solution iteratively rotates the string by slicing it and recomposing it character by character to check if it matches goal.