leetcode 28

来源:互联网 发布:虚拟币交易所源码 编辑:程序博客网 时间:2024/05/19 01:10

Implement strStr().

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


Seen this question in a real interview before?   

Yes
 


我的代码比较复杂,效率也不高,其中应该用数据结构说到过关于字符串匹配的预处理,我没做

结果就是33%的效率,看了别的答案,恩,用javascript内部indexof函数,恩,不错top1

下面两个代码

var strStr = function(haystack, needle) {    if(needle==''){        return 0;    }    if(haystack.length<needle.length || (haystack.length==0 && needle.length!=0)){        return -1;    }    for(var i=0;i<haystack.length;i++){        var flag=0;        for( var j=0;j<needle.length;j++){            if(haystack[i+j]!=needle[j]){                flag=1;                break;            }        }        if(flag==0){            return i;        }    }    return -1;};
/** * @param {string} haystack * @param {string} needle * @return {number} */var strStr = function(haystack, needle) {    return haystack.indexOf(needle);};