28. Implement strStr()

来源:互联网 发布:sai mac软件下载 编辑:程序博客网 时间:2024/06/11 05:18

Implement strStr().

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

给两个字符串,文本串s以及模式串p,现在要查找p在s中的位置,如果找不到则返回-1.

两种解决方案:

暴力搜索

class Solution 

{
public:
    int strStr(string haystack, string needle)
    {

      int len1=haystack.size();

      int len2=needle.size();

      if(len1<len2)

      return -1;

      if(len1==0&&len2==0)

      return 0;

      if(len2==0)

      return 0;

      int i(0);

     int  j(0);

       while(i<len1&&j<len2)

      {

      if(haystack[i]==needle[j])

              {

              i++;

              j++;

              }

      else

            {

               i=i-j+1;

               j=0;

             }

       }

      if(j==len2)

      return  i-j;

     else

     return -1;

     }

};

KMP算法:

class Solution 

{
public:

void NextArray(string &str,vector<int> &next)

{

int len=str.size();

int i=0;//后缀位置

int j=-1;//前缀位置

next[0]=-1;

while(i<len)

{

if(j==-1||str[i]==str[j])

{

i++;

j++;

next[i]=j;

}

else

j=next[j];


}

}

 int strStr(string haystack, string needle)

{

      int len1=haystack.size();

      int len2=needle.size();

      if(len1<len2)

      return -1;

      if(len1==0&&len2==0)

      return 0;

      if(len2==0)

      return 0;

      int i(0);

     int  j(0);

vector<int> next(len2);

NextArray(needle,next);

while(i<len1&&j<len2)

      {

      if(haystack[i]==needle[j])

              {

              i++;

              j++;

              }

      else

            {

               j=next[j];

             }

       }

      if(j==len2)

      return  i-j;

     else

     return -1;



}

};


































原创粉丝点击