Home >Web Front-end >JS Tutorial >Greatest Common Divisor of Strings in Javascript
Today, I solved the second problem of the LeetCode 75 series. I'd like to share how I approached this problem.
Problem Statement:
You are given two strings, str1 and str2. Return the largest string x such that x divides both str1 and str2.
Examples:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Input: str1 = "LEET", str2 = "CODE"
Output: ""
**
My Approach**
I divided my solution into three parts:
Check if a common divisor string exists:
First, I check if a common divisor exists by concatenating str1 str2 and str2 str1.
If the two concatenated strings are not equal, it means there is no common divisor, and the function returns an empty string ("").
Find the GCD length:
Next, I find the GCD of the lengths of str1 and str2.
I use a recursive gcd() function. If b !== 0, the function calls itself recursively with two arguments:
gcd(a, b) = gcd(b, a % b)
Once b = 0, the function returns a, which is the GCD length.
Example Calculation:
Initial Call: gcd(6, 3)
Since b = 3 is not 0, it recursively calls gcd(3, 6 % 3) → gcd(3, 0)
Second Call: gcd(3, 0)
Now b = 0, so the function returns 3.
Extract the GCD substring:
Finally, I extract the substring from str1 using the gcdlength.
function gcdOfStrings(str1, str2) { // recursive function to calculate the GCD of two numbers function gcd(a, b) { console.log(a, b); return b === 0 ? a : gcd(b, a % b); } // Step 1: Check if str1 and str2 match or not if (str1 + str2 !== str2 + str1) { return ""; // No common pattern exists } // Step 2: Find the GCD of the lengths of str1 and str2 const len1 = str1.length; const len2 = str2.length; const gcdLength = gcd(len1, len2); // Step 3: The largest divisor substring return str1.substring(0, gcdLength); } // Example usage: console.log(gcdOfStrings("ABCABC", "ABC")); // Output: "ABC" console.log(gcdOfStrings("ABABAB", "ABAB")); // Output: "AB" console.log(gcdOfStrings("LEET", "CODE")); // Output: ""
If you have better solutions or ideas, feel free to share with me.
The above is the detailed content of Greatest Common Divisor of Strings in Javascript. For more information, please follow other related articles on the PHP Chinese website!