Skip to content

Instantly share code, notes, and snippets.

@codecakes
Last active September 5, 2022 18:04
Show Gist options
  • Save codecakes/c1b1074c33c511b462f94a67aa55d25b to your computer and use it in GitHub Desktop.
Save codecakes/c1b1074c33c511b462f94a67aa55d25b to your computer and use it in GitHub Desktop.
Find if the rotated string2 is same as string1 which may include repeating characters.
# print(is_string_rotate("ABRACADA", "RACADAAB"))
# 1. increment string 1 char count
# 2. check string 2 count, inc & skip until match. if word count doesn't
# match in step 1, move to next character.
# 3. Return to step 1
# 4. Invariant: End when string1 count is exhausted.
def is_string_rotate(string1: str, string2: str) -> bool:
"""Returns True if string is rotated.
"""
n1 = len(string1)
n2 = len(string2)
if n1 != n2:
return False
str1 = ""
str1_count = 0
str2 = ""
str2_count = 0
str2_start_idx = 0
for char_str1_idx, char_str1 in enumerate(string1):
str1 += char_str1
str1_count += 1
# print(f"str1={str1} str1_count={str1_count}")
while str2_count < str1_count and str2_start_idx < n2:
if string2[str2_start_idx] != str1[0]:
str2_start_idx += 1
# print(f"str2_start_idx={str2_start_idx} str2_count={str2_count}")
# start string 2 iteration either where it was left off last i.e.
# str2_start_idx is same but str2_count is next OR
# start from beginning i.e. str2_start_idx is next but str2_count=0
start_string2 = string2[(str2_start_idx+str2_count)%n2:]
enumerate_string2_idx = (str2_start_idx+str2_count)%n2
# print(f"start string2 at {enumerate_string2_idx}={start_string2}")
for char_str2_idx in range(enumerate_string2_idx, enumerate_string2_idx+n2):
char_str2 = string2[char_str2_idx % n2]
# print(f"char_str2={char_str2}")
if char_str2 == str1[str2_count % len(str1)]:
str2 += char_str2
str2_count += 1
else:
str2_start_idx += str2_count
str2 = ""
str2_count = 0
break
if str2_count == str1_count:
break
if str2_start_idx == n2:
return False
print(f"str1={str1} str2={str2}")
return str1 == str2
print(is_string_rotate("ABRACADA", "RACADAAB"))
print(is_string_rotate("ABRACADA", "RACADAAX"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment