[英]Check if a string is made up of multiple occurences of a substring
(JavaScript) 所以,我需要一个函数 checkString(str, substr) 来检查一个字符串是否由给定子字符串的多次出现组成。
例子:
checkString("abc", "abc") -> true
checkString("abcabcabc", "abc") -> true
checkString("abcdef", "abc") -> false
checkString("abcab", "abc) -> true
有人可以帮我吗?
如果空格无关紧要,这是一个解决方案:
const checkString = (bigString, subString) => {
const split = bigString.split(subString);
const onlyOccurances = split.filter(v => v === '');
return split.length === onlyOccurances.length
}
checkString("abc", "abc") // true
checkString("abcabcabc", "abc") // true
checkString("abcdef", "abc") // false
bigString.split(subString)
将大字符串拆分成一个空字符串数组,如果有完美匹配,它的长度就是出现的次数。 如果数组中的任何一个值不是空字符串,则意味着不存在完美匹配,因此空过滤的长度和拆分值的长度之间会有差异。
希望这是有道理的。
此方法将返回一个对象,如果在字符串中找到该值,则 found 为 true,如果多次找到,则 multipleFound 为 true;
const checkString = function(str, v) {
let found = false,
multi = false,
index;
index = str.indexOf(v);
if (index !== -1) {
found = true;
index = str.indexOf(v, index + v.length);
if (index !== -1) {
multi = true;
}
}
return {
found : found,
multipleFound : multi
};
};
这将是检查模式abc
的一种方法:
const rx=/^(abc)+$/; console.log(["abc","abcabcabc","abcdef"].map(t=> `${t} ${rx.test(t)}`))
我强烈建议在 leetcode.com 之类的网站上提高你的算法技能
这是我想出的
function checkString(whole, sub) {
for (let i = 0; i < whole.length; i++) {
if (whole[i] !== sub[i % sub.length]) {
return false;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.