leetcode 1071. Greatest Common Divisor of Strings(python)

524 阅读1分钟

描述

For two strings s and t, we say "t divides s" if and only if s = t + ... + t (t concatenated with itself 1 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: ""

Example 4:

Input: str1 = "ABCDEF", str2 = "ABC"
Output: ""

Note:

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

解析

根据题意,就是找出最大的相同的子字符串。思路简单,就是先遍历找出 str1 和 str2 都能整除的最大数 i ,然后判断 str1[:i] 和 str2[:i] 是否相等,如果相等则直接返回,否则继续进行此过程,如果仍没又找到则返回空字符串。

解答

class Solution(object):
    def gcdOfStrings(self, str1, str2):
        """
        :type str1: str
        :type str2: str
        :rtype: str
        """
        if str1 == str2:
            return str1
        if str1 + str2 != str2 + str1:
            return ''
        if len(str1) < len(str2):
            str1, str2 = str2, str1
        l1, l2 = len(str1), len(str2)
        for i in range(l2, 0, -1):
            if l1 % i != 0 or l2 % i != 0:
                continue
            if str1[:i] == str2[:i]:
                return str1[:i]
        return ""
        	      
		

运行结果

Runtime: 16 ms, faster than 84.41% of Python online submissions for Greatest Common Divisor of Strings.
Memory Usage: 13.3 MB, less than 89.78% of Python online submissions for Greatest Common Divisor of Strings.

原题链接:leetcode.com/problems/gr…

您的支持是我最大的动力