I want to write a code in JavaScript language that can search for the number of repetitions of letters in a word, like this code, but in a shorter 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")
P粉9589860702023-09-14 00:42:16
Use the .substring()
or .slice()
method instead of nested loops.
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"));