LeetCode28:Implement strStr()

来源:互联网 发布:淘宝网鞋子女鞋图片 编辑:程序博客网 时间:2024/05/18 02:57

Implement strStr().

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

题目描述:实现strStr()函数,strStr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的位置;否则,返回-1。

方法一:暴力匹配

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

方法二:KMP字符串匹配算法

//1.首先对模式串needle进行“自匹配”,求出模式串前缀与后缀的最大公共元素长度,并将长度保存到next数组中;//2.根据next数组,对文本串haystack与模式串needle进行字符串匹配class Solution{public:int strStr(string haystack, string needle){int hlen = haystack.length();int nlen = needle.length();int* next = new int[nlen];getNext(needle, next);int i = 0;int j = 0;while (i < hlen&&j < nlen){//如果j=-1,或者当前字符匹配成功(即haystack[i] == needle[j]),则继续匹配后面的字符if (j == -1 || haystack[i] == needle[j]){i++;j++;}else{    //如果j不等于-1,且当前字符匹配失败,则i不变,j=next[j],模式串的needle[next[j]]字符与文本串haystack[i]进行匹配j = next[j];}}if (j == nlen)   //模式串与文本串中某个子串完全匹配成功return i - nlen;elsereturn -1;}       //对模式串needle进行自匹配,计算KMP算法的next数组void getNext(string &needle1, int next[]){int nlen = needle1.size();next[0] = -1;int k = -1;int j = 0;while (j < nlen - 1){//needle[k]表示前缀,needle[j]表示后缀if (k == -1 || needle1[j] == needle1[k]){++k;++j;next[j] = k;}else{k = next[k];//通过递归前缀索引,找到长度更短的相同前缀后缀}}}};


完整测试代码:

#include<iostream>#include<string>using namespace std;//1.首先对模式串needle进行“自匹配”,求出模式串前缀与后缀的最大公共元素长度,//并将长度保存到next数组中;//2.根据next数组,对文本串haystack与模式串needle进行字符串匹配class Solution{public:int strStr(string haystack, string needle){int hlen = haystack.length();int nlen = needle.length();int* next = new int[nlen];getNext(needle, next);int i = 0;int j = 0;while (i < hlen&&j < nlen){//如果j=-1,或者当前字符匹配成功(即haystack[i] == needle[j]),则继续匹配后面的字符if (j == -1 || haystack[i] == needle[j]){i++;j++;}else{    //如果j不等于-1,且当前字符匹配失败,则i不变,j=next[j],模式串的needle[next[j]]字符与文本串haystack[i]进行匹配j = next[j];}}if (j == nlen)   //模式串与文本串中某个子串完全匹配成功return i - nlen;elsereturn -1;}       //对模式串needle进行自匹配,计算KMP算法的next数组void getNext(string &needle1, int next[]){int nlen = needle1.size();next[0] = -1;int k = -1;int j = 0;while (j < nlen - 1){//needle[k]表示前缀,needle[j]表示后缀if (k == -1 || needle1[j] == needle1[k]){++k;++j;next[j] = k;}else{k = next[k];//通过递归前缀索引,找到长度更短的相同前缀后缀}}}};int main(){string s = "ABC ABCDAB ABCDABCDABDE";//string s = "ABCDABD";string p = "ABCDABD";Solution sol;int n = sol.strStr(s, p);cout << n << endl;system("pause");return 0;}



0 0
原创粉丝点击