Created
March 12, 2024 23:33
-
-
Save nuxy/28cfe8a019dca5c506e221f39f8215d6 to your computer and use it in GitHub Desktop.
LeetCode > 1071. Greatest Common Divisor of Strings (JavaScript solution)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Greatest Common Divisor of Strings | |
* | |
* @param {String} str1 | |
* String of characters. | |
* | |
* @param {String} str2 | |
* String of characters. | |
* | |
* @return {String} | |
* | |
* @see https://leetcode.com/problems/greatest-common-divisor-of-strings/description/?envType=study-plan-v2&envId=leetcode-75 | |
*/ | |
const gcdOfStrings = function(str1, str2) { | |
const regex = new RegExp(`${str2}(?=${str2})?`, 'g'); | |
return str1.match(regex) && (str1.replace(regex, '') || str2) || ''; | |
}; | |
gcdOfStrings('ABCABC', 'ABC'); // ABC | |
gcdOfStrings('ABABAB', 'ABAB'); // AB | |
gcdOfStrings('LEET', 'CODE'); // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Runtime benchmark with jsPerf