Created
August 7, 2016 05:30
-
-
Save humbroll/68b6e4b9dda5cb73d7b3368dd6b50ea3 to your computer and use it in GitHub Desktop.
String Roatation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# String Roatation | |
# Assume you have a method isSubstring which checks if one word is a substring of another. | |
# Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call | |
# to isSubstring(e.g., "waterbottle" is a rotation of "erbottlewat") | |
class StringRotation: | |
def __init__(self, str_val): | |
self.str_val = str_val | |
def is_substring(self, sub_str): | |
result = False | |
starting_index = 0 | |
for i, c in enumerate(sub_str): | |
if result and c != self.str_val[(i-starting_index)] and self.str_val[0] != c: | |
result = False | |
elif self.str_val[0] == c: | |
starting_index = i | |
result = True | |
if sub_str[:(starting_index)] != self.str_val[len(self.str_val)-starting_index:]: | |
result = False | |
return result | |
if __name__ == '__main__': | |
# org_str = "waterbottle" | |
org_str = "waterbottleiswaterbottle" | |
string_rotation = StringRotation(org_str) | |
# sub_str = "erbottlewat" | |
sub_str = "ottleiswaterbottlewaterb" | |
print "%s is a substring of %s? : %s" % \ | |
(sub_str, org_str, string_rotation.is_substring(sub_str)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment