[LeetCode] # 1071 Greatest Common Divisor of Strings
1 min readMar 11, 2020
Environment: Python 3.7
Key technique: Recursive Method
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Solution:
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
l1, l2 =len(str1),len(str2)
if l1==0 :return str2
if l1<l2 :return self.gcdOfStrings(str2,str1)
if str1[0:l2] !=str2: return ""
return self.gcdOfStrings(str1[l2:],str2)
Submitted result:
Lesson learn:
Recursive Method can reduce code number and better than two for loop.
Reference: