2023-02-01 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp
.
February LeetCoding Challenge 1
Description
Greatest Common Divisor of Strings
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
andstr2
consist of English uppercase letters.
Solution
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
if(str1.length() < str2.length()) {
swap(str1, str2);
}
int pos1 = 0;
int pos2 = 0;
int len1 = str1.length();
int len2 = str2.length();
while(pos1 < len1) {
if(str1[pos1] != str2[pos2]) return "";
pos1 += 1;
pos2 = (pos2 + 1) % len2;
}
if(pos2 == 0) return str2;
return gcdOfStrings(str2, str2.substr(pos2));
}
};
// Accepted
// 114/114 cases passed (3 ms)
// Your runtime beats 83.39 % of cpp submissions
// Your memory usage beats 78.21 % of cpp submissions (7.1 MB)