【朱迪的LeetCode刷题笔记】】1071. Greatest Common Divisor of Strings #Python ...
本帖最后由 Judie 于 2023-5-31 22:40 编辑For two strings s and t, we say "t divides s" if and only if s = 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.
Judy
Python stupid way calculating gcd
class Solution(object):
def gcdOfStrings(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
l1 = len(str1)
l2 = len(str2)
l0 = min(l1, l2)
r = ""
for i0 in range(1,l0+1):
if l1 % i0 == 0 and l2 % i0 == 0 and str1[:i0] == str2[:i0] and str1.count(str1[:i0]) == l1 / i0 and str2.count(str2[:i0]) == l2 / i0:
r = str2[:i0]
return r
Sol1
Python amazing approach!
https://leetcode.com/problems/greatest-common-divisor-of-strings/solutions/3124806/beats-100-easy-with-video-java-c-python/?envType=study-plan-v2&envId=leetcode-75
class Solution(object):
def gcdOfStrings(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
def gcd(int1, int2):
if (int2 == 0):
return int1
else:
return gcd(int2, int1 % int2)
if str1 + str2 != str2 + str1:
return ""
maxlen = gcd(len(str1), len(str2))
return str1[:maxlen]
Gray
C++ smarter way calculating gcd
class Solution {
public:
int gcd(int a, int b) // The function runs recursive in nature to return GCD
{
if (a == 0) // If a becomes zero
return b; // b is the GCD
if (b == 0)// If b becomes zero
return a;// a is the GCD
if (a == b) // The case of equal numbers
return a; // return any one of them
// Apply case of substraction
if (a > b) // if a is greater subtract b
return gcd(a-b, b);
return gcd(a, b-a); //otherwise subtract a
}
string gcdOfStrings(string str1, string str2) {
int c = gcd(str1.size(),str2.size());
bool test = true;
string temp = str2.substr(0,c);
for(int i = 0; i < str1.size()/c; i++){
if(str1.substr(ic,c) != temp){
return "";
}
}
for(int i = 0; i < str2.size()/c; i++){
if(str2.substr(ic,c) != temp){
return "";
}
}
return temp;
}
};
页:
[1]