LeetCode 1071. Maximum common factor of string (python)

Keywords: Lambda

Title Link

Title Description:

For strings S and T, only if S = T +... +Only when t (t is connected to itself once or more), can we determine that "t can eliminate s".

Returns the string x, which requires that x can divide str1 and X can divide str2.

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:

Input: str1 = "abaab", str2 = "ABAB"
Output: "AB"
Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: "

Tips:

1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] and str2[i] are capital letters

Solutions:
Double cycle
First, determine whether the current string is a common prefix (such as A,AB,ABC).
If it is a common prefix, it is judged whether the string can form str1 and str2 circularly.
This method takes a long time

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        res=''
        i=0
        while i<min(len(str1),len(str2)):
            x=str1[:i+1]
            if str1[:i+1]!=str2[:i+1]:
                break
            else:
                rr=x
                flag1,flag2=0,0
                while len(rr)<=len(str1):
                    if rr==str1:
                        flag1=1
                    rr+=x
                rr=x   
                while len(rr)<=len(str2):
                    if rr==str2:
                        flag2=1
                    rr+=x
                    
                if flag1==1 and flag2==1:
                    res=x
            i+=1
        return res


Answer in comment area:
Execution time 32ms

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        if len(str1) < len(str2):
            str1, str2 = str2, str1#Assign a short string to str2
        len_str1 = m = len(str1)
        len_str2 = n = len(str2)
        res = ''
        while n > 0:
            m, n = n, m%n#Finding the greatest common factor by division of rolling
        gcd = m
        rep1, rep2 = str1[:gcd], str2[:gcd]
        #Determine whether the prefixes corresponding to the greatest common factor are equal, and whether the strings str1 and str2 can be formed.
        if rep1 == rep2 and str1 == len_str1//gcd *rep1 and str2 == len_str2//gcd*rep2:
            return rep1
        return res

Comment area method 2:

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        sort_str = lambda s1, s2: (s2, s1) if len(s2) > len(s1) else (s1, s2)
        long, short = sort_str(str1, str2)#Long for long, short for short
        while long != short:
            if short not in long:
                return ''
            long = long.replace(short, '', 1)#Delete the short from the long
            long, short = sort_str(short, long)
        return short

Posted by trev on Tue, 29 Oct 2019 13:56:12 -0700