For two strings
s
and t
, we say "t
divides s
" if and only if s = t + ... + t
(t
concatenated with itself 1 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"
Approach
Java
public class GreatestCommonDivisor {public static void main(String[] args) {String str1 = "ABCABC", str2 = "ABC";System.out.println(gcdOfStrings(str1, str2));}static String gcdOfStrings(String str1, String str2) {if (!(str1 + str2).equals(str2 + str1))return "";return str1.substring(0, gcd(str1.length(), str2.length()));}// function to find the gcd of// two numbersstatic int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the gcd of//two numbersint gcd(int a, int b){if (b == 0)return a;return gcd(b, a % b);}string gcdOfStrings(string str1, string str2){if (str1 + str2 != str2 + str1)return "";return str1.substr(0, gcd(str1.size(), str2.size()));}int main(){string str1 = "ABCABC", str2 = "ABC";cout << gcdOfStrings(str1, str2);return 0;}
No comments:
Post a Comment