原题说明
For strings S and T, we say “T divides S“ if and only if S = T + … + T (T concatenated with itself 1 or more times)
Return the largest string X such that X divides str1 and X divides 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: “”
Note:
1 <= str1.length <= 10001 <= str2.length <= 1000str1[i]andstr2[i]are English uppercase letters.
解题思路
这道题可以用递归来求解,和求两个数的最大公约数类似。
首先,str1和str2(假设str1.size() >= str2.size())有最大公约数的必要条件是str1的前缀等于str2。
原因如下,假设最大公约字符串为divisor_str,那么str1 = x * divisor_str,str2 = y * divisor_str (x, y为正整数,且x >= y),
所以str1的前y个divisor_str就等于str2。
其次,我们希望求两个字符串的最大公约字符串,就等于求两个字符串之差和其中一个字符串的最大公约字符串。还是用上述例子:str1与str2的最大公约数,也是str1 - str2 = (y - x) * divisor_str 与 str2 = y * divisor_str的最大公约数。
当y = x时,str2本身即为str1和str2的最大公约数。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(M + N), M和N为str1和str2的长度, 主要是str1.substr(0, str2.size()) != str2这一判断会遍历一遍每一个字符
空间复杂度: O(1), 栈的最大深度为O(max(M, N)), 因为最坏的情况len(str2) = 1,那么递归深度就是len(str1), 即O(M).
视频讲解
我们在Youtube上更新了视频讲解,欢迎关注!