英文:
use function search substring js
问题
function shortSearch(long, short){
let count = 0;
for(let i = 0; i < long.length - short.length + 1; i++){
if(long.substring(i, i + short.length) === short) count++;
}
return count;
}
shortSearch("lorielol loled", "lol");
英文:
I want to write a code in the JavaScript language that searches for the number of repetitions of letters in a word, like this code, but in a short way o(n).
function naiveSearch(long, short){
var count = 0;
for(var i = 0; i < long.length; i++){
for(var j = 0; j < short.length; j++){
if(short[j] !== long[i+j]) break;
if(j === short.length - 1) count++;
}
}
return count;
}
naiveSearch("lorielol loled", "lol")
答案1
得分: 1
使用`.substring()`或`.slice()`方法而不是嵌套循环。
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function naiveSearch(long, short) {
var count = 0;
for (var i = 0, limit = long.length - short.length; i < limit; i++) {
if (long.substring(i, i + short.length) == short) {
count++;
}
}
return count;
}
console.log(naiveSearch("lorielol loled", "lol"));
<!-- end snippet -->
这仍然是O(n*m)。你在主循环中进行了O(n)次迭代,而子字符串和比较都是O(m)。
英文:
Use the .substring()
or .slice()
method rather than a nested loop.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function naiveSearch(long, short) {
var count = 0;
for (var i = 0, limit = long.length - short.length; i < limit; i++) {
if (long.substring(i, i + short.length) == short) {
count++;
}
}
return count;
}
console.log(naiveSearch("lorielol loled", "lol"));
<!-- end snippet -->
This is still O(n*m). You do O(n) iterations of the main loop, and the substrings and comparisons are each O(m).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论