Rotate String

Easy· string doubling

Problem

A rotation moves the first character of a string to its end. Decide whether some number of rotations can turn string s into string goal.

Examples

Input: s = "abcde", goal = "deabc"
Output: true
Rotating three times gives "deabc".
Input: s = "abcde", goal = "abced"
Output: false

Constraints

  • • 1 <= s.length, goal.length <= 100
  • • Lowercase English letters only

Hints & approach

Hint 1

Write down every rotation of "abc". Where do they all appear together?

Hint 2

Every rotation of s is a substring of s + s.

Approachtry the hints first

If the lengths differ, return false. Otherwise, every rotation of s appears as a length-n window inside s + s, so the answer is whether goal is a substring of s + s. With a linear-time matcher such as KMP this is O(n); a built-in substring search is fine for the given limits.

Time O(n) · Space O(n)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.