28. 找出字符串中第一个匹配项的下标

题目描述:

在这里插入图片描述

主要思路:

实现一:直接find

class Solution {
    
    
public:
    int strStr(string haystack, string needle) {
    
    
        if(haystack.find(needle)>=haystack.length())
            return -1;
        else return haystack.find(needle);
    }
};

实现二:KMP

class Solution {
    
    
public:
    int strStr(string haystack, string needle) {
    
    
        int n=haystack.length(),m=needle.length();
        vector<int> ne(m+1);
        haystack=" "+haystack;
        needle=" "+needle;
        // 寻找公共前后缀的位置
        for(int i=2,j=0;i<=m;++i)
        {
    
    
            while(j&&needle[i]!=needle[j+1]) j=ne[j];
            if(needle[i]==needle[j+1]) ++j;
            ne[i]=j;
        }
        for(int i=1,j=0;i<=n;++i)
        {
    
    
            while(j&&haystack[i]!=needle[j+1]) j=ne[j];
            if(needle[j+1]==haystack[i]) ++j;
            if(j==m)
            {
    
    
                return i-j;
            }
        }
        return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_54385104/article/details/129666039