🌟

Python勉強日記:2/75

2025/02/20に公開

今日の問題

# 最大公約数を求める問題
For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times).

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

 

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: ""
 

Constraints:

1 <= str1.length, str2.length <= 1000
str1 and str2 consist of English uppercase letters.

解答

class Solution(object):
    def gcdOfStrings(self, str1, str2):
        """
        :type str1: str
        :type str2: str
        :rtype: str
        """
        # Check if there is a common repeating pattern
        if str1 + str2 != str2 + str1:
            return ""
        # 2つの文字列を並べたとき、入れ替えても同じ文字列になるならOK
        
        # Find the GCD of the lengths of str1 and str2
        def gcd(a, b):
            while b:
                a, b = b, a % b
            return a
        # ユークリッドの互除法のやり方を事前に定義
        
        gcd_length = gcd(len(str1), len(str2))
        # ユークリッドの互除法に当てはめる値を定義
        
        # Return the common substring of length gcd_length
        return str1[:gcd_length]
        # gcd_lengthより前の文字列をreturnする

こんな感じ

Discussion