LeetCode 题解工作台

字符串的最大公因子

对于字符串 s 和 t ,只有在 s = t + t + t + ... + t + t ( t 自身连接 1 次或多次)时,我们才认定 “ t 能除尽 s ”。 给定两个字符串 str1 和 str2 。返回 最长字符串 x ,要求满足 x 能除尽 str1 且 x 能除尽 str2 。 示例 1…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·string

bolt

答案摘要

class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

对于字符串 s 和 t,只有在 s = t + t + t + ... + t + tt 自身连接 1 次或多次)时,我们才认定 “t 能除尽 s”。

给定两个字符串 str1 和 str2 。返回 最长字符串 x,要求满足 x 能除尽 str1x 能除尽 str2

 

 

示例 1:

输入:str1 = "ABCABC", str2 = "ABC"

输出:"ABC"

示例 2:

输入:str1 = "ABABAB", str2 = "ABAB"

输出:"AB"

示例 3:

输入:str1 = "LEET", str2 = "CODE"

输出:""

示例 4:

输入:str1 = "AAAAAB", str2 = "AAA"

输出:""

 

提示:

  • 1 <= str1.length, str2.length <= 1000
  • str1 和 str2 由大写英文字母组成
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        def check(a, b):
            c = ""
            while len(c) < len(b):
                c += a
            return c == b

        for i in range(min(len(str1), len(str2)), 0, -1):
            t = str1[:i]
            if check(t, str1) and check(t, str2):
                return t
        return ''
speed

复杂度分析

指标
时间O(m + n)
空间O(m + n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate understands string manipulation and divisibility patterns.

  • question_mark

    Candidate shows awareness of efficiency in checking string prefixes.

  • question_mark

    Candidate demonstrates clear reasoning in validating the divisor.

warning

常见陷阱

外企场景
  • error

    Forgetting that the greatest common divisor must be a prefix of both strings.

  • error

    Not checking for an empty string result when no common divisor is found.

  • error

    Assuming the solution always involves finding a non-empty divisor string.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if both strings have no common divisor?

  • arrow_right_alt

    What if one string is a multiple of the other, but not a perfect divisor?

  • arrow_right_alt

    How does the problem change if strings contain lower case letters?

help

常见问题

外企场景

字符串的最大公因子题解:数学·string | LeetCode #1071 简单