使用 JavaScript 的搜索子字符串函数。

huangapple go评论68阅读模式
英文:

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 &lt; long.length; i++){
        for(var j = 0; j &lt; short.length; j++){
           if(short[j] !== long[i+j]) break;
           if(j === short.length - 1) count++;
        }
    }
    return count;
}
naiveSearch(&quot;lorielol loled&quot;, &quot;lol&quot;)

答案1

得分: 1

使用`.substring()`或`.slice()`方法而不是嵌套循环。

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    function naiveSearch(long, short) {
      var count = 0;
      for (var i = 0, limit = long.length - short.length; i &lt; limit; i++) {
        if (long.substring(i, i + short.length) == short) {
          count++;
        }
      }
      return count;
    }

    console.log(naiveSearch(&quot;lorielol loled&quot;, &quot;lol&quot;));

&lt;!-- end snippet --&gt;

这仍然是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 &lt; limit; i++) {
    if (long.substring(i, i + short.length) == short) {
      count++;
    }
  }
  return count;
}

console.log(naiveSearch(&quot;lorielol loled&quot;, &quot;lol&quot;));

<!-- 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).

huangapple
  • 本文由 发表于 2023年4月7日 04:45:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定