Learner Level
Implement the checkStringRotation method that checks whether one string is a rotation of another string.
The input contains two strings, first and second. Your task is to check whether second can be created by rotating first.
A rotation moves characters from the beginning of a string to the end without changing their order. For example, waterbottle rotated by five characters becomes erbottlewat.
Example 1
Input
first (string) =
waterbottlesecond (string) =
erbottlewatReturns (boolean)
trueExample 2
Input
first (string) =
abcdesecond (string) =
cdeabReturns (boolean)
trueExample 3
Input
first (string) =
abcdesecond (string) =
abcedReturns (boolean)
falseTwo strings can be rotations only if they have the same length.
If second is a rotation of first, it must appear inside first + first. Doubling the first string contains every possible rotation as a substring.
So, first compare lengths, then check whether the second string exists in the doubled string.
Pseudocode:
function checkStringRotation(first, second):
if length(first) != length(second):
return false
doubled = first + first
if doubled contains second:
return true
return falseReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run