Skip to content

Commit 318faf0

Browse files
committed
update 1.9 soln
1 parent 5ae7a52 commit 318faf0

File tree

1 file changed

+4
-28
lines changed

1 file changed

+4
-28
lines changed

Python/chapter01/1.9 - String Rotation/miguel_1.9_sol.py

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,9 @@ def string_rotation(s1: str, s2: str) -> bool:
2525
"""
2626
Given two strings, string_rotation will check if s2 is a rotation of s1
2727
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)
3731
Space Complexity: O(1)
3832
:param s1: the rotated string
3933
:param s2: the original string
@@ -42,25 +36,7 @@ def string_rotation(s1: str, s2: str) -> bool:
4236
# not rotation if lengths don't match
4337
if len(s1) != len(s2):
4438
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)
6440

6541

6642
class TestStringRotation(unittest.TestCase):

0 commit comments

Comments
 (0)