Skip to content

Latest commit

 

History

History
70 lines (48 loc) · 1.62 KB

_1071. Greatest Common Divisor of Strings.md

File metadata and controls

70 lines (48 loc) · 1.62 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : September 25, 2024

Last updated : September 25, 2024


Related Topics : Math, String

Acceptance Rate : 52.7 %


Solutions

Python

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        if str1 + str2 != str2 + str1 :
            return ''

        return str1[:gcd(len(str1), len(str2))]
class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        tryLen = 0

        # set str1 as shorter
        if len(str1) > len(str2) :
            str1, str2 = str2, str1

        while tryLen < len(str1) and str1[tryLen] == str2[tryLen] :
            tryLen += 1

        # len of x
        for i in range(tryLen, -1, -1) :
            if not i :
                break

            if len(str1) % i or len(str2) % i :
                continue

            if any(str1[j] != str1[j % i] or 
                   str2[j] != str1[j % i] for j in range(i, len(str1))) :
                continue

            if any(str2[j] != str2[j % i] for j in range(len(str1), len(str2))) :
                continue

            return str1[:i]

        return ''