• 28. Implement strStr()


    28. Implement strStr()

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

     1 /**
     2  * @param {string} haystack
     3  * @param {string} needle
     4  * @return {number}
     5  */
     6 var strStr = function(haystack, needle) {
     7     //题目是想求needle是不是haystack是子串。是的话返回开始匹配的index,否者就返回-1
     8     
     9     //暴力的写法就是全部都试过一边,不过kmp是比较好的实现方式
    10     //kmp算法最难的是next表的建立
    11     
    12     function next(pattern){
    13         
    14         var next = [];        
    15         var len = pattern.length; 
    16         next[0] = -1;
    17         
    18         var k = -1;
    19         var j = 0;
    20         
    21         while(j < len-1){
    22             
    23             //此刻,k即next[j-1],且pattern[k]表示前缀,pattern[j]表示后缀
    24             //注:k==-1表示未找到k前缀和k后缀相等,首次分析可先忽略
    25             
    26             if(k == -1 || pattern[j] == pattern[k]){            
    27                 ++j;
    28                 ++k;
    29                 next[j] = k;
    30             }else{  //pattern[j] 与 pattern[k]不相等,则继续递归计算前缀p[next[k]]
    31                 
    32                 k = next[k];
    33             }
    34             
    35         }
    36         return next;
    37     }
    38     
    39     var next = next(needle);
    40     
    41     var i = 0,j = 0;
    42     
    43     while(i < haystack.length && j < needle.length){
    44         
    45        //当j=-1时,要移动的是i,当然j也要归0
    46         if(j == -1 || haystack[i] == needle[j]){
    47             
    48             i++;
    49             j++;
    50             
    51         }else{
    52             
    53             //i不需要回溯了
    54             //i = i - j +  1;
    55             
    56             j = next[j]; //j回到指定位置
    57         
    58         }
    59         
    60     }
    61     
    62     if(j == needle.length){
    63         
    64         return i - j;
    65         
    66     }else{
    67         
    68         return -1;
    69     }
    70     
    71 };
  • 相关阅读:
    文件类型的判断
    VS 2003 源码配置管理(subversion+apache)
    DataView
    sql server 挂起的文件操作
    关于权限设计的轻量级实现
    各种类型文件在SQL Server中存储的解决方案
    免费或开源的项目管理工具
    UML中的用例(Use Case)概念分析及实例
    大对象的存储
    用js实现同一页面多个运动效果
  • 原文地址:https://www.cnblogs.com/huenchao/p/7687718.html
Copyright © 2020-2023  润新知