在 JavaScript 中查找两个字符串的 gcd
在数系统中,两个数的最大公约数(GCD)是将两个数相除的最大数。类似地,如果我们将此概念应用于字符串,则两个字符串的gcd是两个字符串中都存在的最大子字符串(长度最大)。
例如-
如果两个字符串是-
const str1 = 'abcabc'; const str2 = 'abc';
那么这些字符串的gcd将是-
const gcd = 'abc';
我们需要编写一个JavaScript函数,它接受两个字符串str1和str2并计算并返回它们的gcd。
示例
此代码将是-
const str1 = 'abcabc';
const str2 = 'abc';
const findGCD = (str1 = '', str2 = '') => {
if (str1 + str2 !== str2 + str1){
//不可能
//没有共同元素
return "";
} else if (str1 == str2){
return str1;
} else if (str1.length > str2.length){
return findGCD(str1.slice(str2.length), str2);
} else {
return findGCD(str2.slice(str1.length), str1);
}
};
console.log(findGCD(str1, str2));输出结果控制台中的输出将是-
abc
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短