python刷LeetCode:1071. 字符串的最大公因子
作者:互联网
难度等级:简单
题目描述:
对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
示例 1:
输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"
示例 2:
输入:str1 = "ABABAB", str2 = "ABAB"
输出:"AB"
示例 3:
输入:str1 = "LEET", str2 = "CODE"
输出:""
提示:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] 和 str2[i] 为大写英文字母
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
思路一:通过对比遍历比较
思路二:通过统计字符串在长字符串中的个数,且个数与 len(s)/len(ss) 相等
解题代码:
# 法一: # 暴力比较,注意全部为同一字符的字符串 class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: len1 = len(str1) len2 = len(str2) if len1 > len2: str1, str2 = str2, str1 len1, len2 = len2, len1 min_len = min(len1, len2) rt = '' for i in range(min_len): cur_s1 = str1[:i+1] flag = 1 for k in range(i+1, len1, i+1): if str1[k :k+i+1] != cur_s1: flag=0 break for k in range(0, len2, i+1): if str2[k :k+i+1] != cur_s1: flag=0 break if flag: rt = cur_s1 return rt # 法二: class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: len1 = len(str1) len2 = len(str2) if len1 > len2: str1, str2 = str2, str1 len1, len2 = len2, len1 min_len = min(len1, len2) rt = '' for i in range(min_len): cur_s1 = str1[:i+1] len_curs1 = len(cur_s1) if (len1/len_curs1 == str1.count(cur_s1)) and (len2/len_curs1 == str2.count(cur_s1)): # 字符串个数与 长度之商相等 rt = cur_s1 return rt
标签:python,str2,str1,len,1071,len2,len1,LeetCode,s1 来源: https://www.cnblogs.com/jaysonteng/p/12487474.html