Skip to content

实现strStr #4

@AILINGANGEL

Description

@AILINGANGEL

输入: haystack 和 needle两个字符串,找出needle在haystack中的位置,如果不存在就返回-1;如果needle是空字符串就返回0;

这是一个字符串匹配的问题,下面的解法是遇到不相等的就将j重置为0,将i设置为下一个;更聪明的做法是采取KMP算法,i的值不用每次都加一, j也不用回到起始位置,避免了无畏的比较.

var strStr = function(haystack, needle) {
    let hlen = haystack.length;
    let nlen = needle.length;
    let i = 0, j = 0;
    while(i < hlen - nlen + 1 && j < nlen) {
        if(haystack[i+j] === needle[j]) {
            j++;
        } else {
            i++;
            j = 0;
        }
    }
    if(j === nlen) {
        return i;
    }
    return -1;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions