leetcode题集: 28. Implement strStr()

24 篇文章 0 订阅

第14题: 28. Implement strStr()

 题目大意:给出两个字符串,求解待匹配串在主串中的位置,如果不是主串的一个子串,则返回-1;如果待匹配串为空的话,则返回0;这与C 中的strsstr()函数一致。

题目分析:一个字符串匹配的求解。第一个印象就是想到了KMP算法,字符串匹配。但是抱着试一试的心理,也用暴力法做了一个求解。

暴力法求解:直接莽,看代码:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1 = haystack.size();
        int len2 = needle.size();
        if(len2==0) return 0;
        int j=0;
        for(int i=0;i<len1;i++){
            if(haystack[i]==needle[0]){
                for(j=1;j<len2;j++){
                    if(needle[j]!=haystack[i+j]) break;
                }
                if(j==len2) return i;
            }
        }
        return -1;
    }
};

 emmmm出乎意料的竟然也通过了,只不过这个时间确实有点真实。至于内存,是因为用了几个额外的变量能存储字符串长度等参数,内存都相差无几。

KMP算法求解:KMP分析过程见另一篇博客,KMP算法和字符串匹配 这里直接上代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1 = haystack.size();
        int len2 = needle.size();
        if(len2==0) return 0;
        int *next = (int *)malloc(sizeof(int)*len2);    // next数组
        next[0] = -1;
        int j=-1;
        for(int i=0;i<len2-1;){    // next数组求解过程
            if(j==-1 || needle[i]==needle[j]){
                i++;
                j++;
                next[i] = j;
            } else {
                j = next[j];
            }
        }
        j = 0;
        for(int i=0;i<len1;){       //KMP算法字符串匹配
            if(j==-1 || haystack[i]==needle[j]){
                i++;
                j++;
            } else {
                j=next[j];
            }
            if(j==len2) return i-j;    // 返回主串中起始匹配位置
        }
        return -1;
    }
};

 时间果然快了很多,KMP算法名不虚传。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值