Skip to content

Instantly share code, notes, and snippets.

@nuxy
Created March 12, 2024 23:33
Show Gist options
  • Save nuxy/28cfe8a019dca5c506e221f39f8215d6 to your computer and use it in GitHub Desktop.
Save nuxy/28cfe8a019dca5c506e221f39f8215d6 to your computer and use it in GitHub Desktop.
LeetCode > 1071. Greatest Common Divisor of Strings (JavaScript solution)
/**
* 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'); //
@nuxy
Copy link
Author

nuxy commented Mar 15, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment