@@ -25,15 +25,9 @@ def string_rotation(s1: str, s2: str) -> bool:
25
25
"""
26
26
Given two strings, string_rotation will check if s2 is a rotation of s1
27
27
using only one call to isSubstring.
28
- We will loop through the original string and compare chars of
29
- rotated string. At the first character equality, we will
30
- compare the rest of the original string to the rotated
31
- string's substring of the same length.
32
- If they match, then we save the index of the
33
- rotated string + 1, and if whatever is left of
34
- s1 is a substring of s2, then we must have a
35
- rotation since we compared the complementary part already.
36
- Runtime: Worst case: O(n^2)
28
+ If s2 is a rotation of s1, then when we add s1 to itself, s2
29
+ must be a substring of s1 + s1
30
+ Runtime: O(n)
37
31
Space Complexity: O(1)
38
32
:param s1: the rotated string
39
33
:param s2: the original string
@@ -42,25 +36,7 @@ def string_rotation(s1: str, s2: str) -> bool:
42
36
# not rotation if lengths don't match
43
37
if len (s1 ) != len (s2 ):
44
38
return False
45
- # if they match, but both empty, return true
46
- if s1 == '' and s2 == '' :
47
- return True
48
- size = len (s1 )
49
- start_idx = - 1
50
- for i , c in enumerate (s2 ):
51
- if c != s1 [0 ]:
52
- continue
53
- # check if substring in s2 from i to the end
54
- # matches s1 from beginning to remaining length of s2
55
- if s2 [i :] == s1 [0 :size - i ]:
56
- # store starting idx of remaining substring in s2
57
- start_idx = size - i
58
- break
59
- if start_idx == - 1 :
60
- return False
61
- if is_substring (s1 [start_idx :], s2 ):
62
- return True
63
- return False
39
+ return is_substring (s2 , s1 + s1 )
64
40
65
41
66
42
class TestStringRotation (unittest .TestCase ):
0 commit comments