您的位置:首页 > 其它

LeetCode28:Implement strStr()

2015-12-01 10:39 495 查看
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;
else
return -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;
else
return -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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: