1.模式匹配

实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
思路:这是一个典型的模式匹配,就是用一个字符串匹配另一个字符串,这里设字符串A和B,就是让A的每一个字符和B的每一个字符比较,当两字符不一样时进行回退,A回到最开始匹配时的下一个字符,B回退到第一个字符。

#include<iostream>
#include<string>
using namespace std;
int strStr(string haystack,string needle);
int main()
{
    cout << strStr("hello","ol");
    return 0;
}
int strStr(string haystack,string needle)
{
    int d=0,i=0,j=0;
    if(needle==" ")
    	return 0;
    while((haystack[i]!='\0')&&(needle[j]!='\0'))
         if(haystack[i]==needle[j])
         {
            i++;
            j++;
         }
         else
        {
            d++;
            i=d,
            j=0;
        }
    if(d<i&&j==needle.size())
      	return d;
    else
    	return -1;
}

改进:因为回退的程度太大次数多所以,有一个kmp算法,这个算法的主要思路是让A字符串不回退至让B回退部分即可,难点就是就算匹配串的next数组。

#include<iostream>
#include<string>
using namespace std;
void next(string t,int a[]);
int strStr(string haystack,string needle);
int main()
{
    cout << strStr("heghhhllo","hhll");
     return 0;
}
int strStr(string haystack,string needle)
{
	if(needle==" ")
    	return 0;
    int*next1=new int [needle.size()];
    int i=0,j=0;
    next(needle,next1);
    while((haystack[i]!='\0')&&(needle[j]!='\0'))
         if(haystack[i]==needle[j])
         {
            i++;
            j++;
         }
         else
        {
            j=next1[j];
            if(j==-1)
            {
             i++;
             j++;
            }
        }
    if( j==needle.size())
      	return i-needle.size()+1;
    else
    	return -1;
}
void next(string t,int a[]){
   a[0]=-1;
   int k=-1,i=0;
   while(t[i]!='\0')
   {
     if(k==-1)
     {
        a[++i]=0;k=0;
     }
     else if(t[i]==t[k])
        a[++i]=++k;
     else
        k=a[k];
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值