-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-gcd.py
More file actions
55 lines (41 loc) · 1.6 KB
/
string-gcd.py
File metadata and controls
55 lines (41 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from fractions import gcd
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# Check that the shorter string exists within the longer string
if (str1 not in str2) and (str2 not in str1):
return ""
# Find the GCD of both strings, which is the max pattern length
maxLength = gcd(len(str1), len(str2))
# Find the basic pattern in each string
pattern1 = findDivisor(str1, maxLength)
pattern2 = findDivisor(str2, maxLength)
# Make sure the basic patterns match
if pattern1 != pattern2:
return ""
# Divide the lengths of both strings by the length of the pattern, then calculate GCD
# The result is the number of times the pattern can repeat
patternCount = gcd((len(str1)/len(pattern1)), (len(str2)/len(pattern1)))
greatestCommonString = pattern1 * int(patternCount)
return greatestCommonString
def findDivisor(s: str, l: float) -> str:
count = 0
# Start building the pattern with the first character of s
sPattern = s[0]
# Create a test case by moving the first character of s to the end
sTest = s[1:] + s[0]
while (sTest != s) and (count < l):
sPattern += sTest[0]
sTest = sTest[1:] + sTest[0]
count += 1
return sPattern
def main():
str1 = "ABCABCABCABCABCABCABCABCD"
str2 = "ABCABCABCABC"
#str1 = "ABABAB"
#str2 = "ABAB"
#str1 = "LEET"
#str2 = "CODE"
sol = Solution()
print(sol.gcdOfStrings(str1, str2))
if __name__ == "__main__":
main()