实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
思路:这是一个典型的模式匹配,就是用一个字符串匹配另一个字符串,这里设字符串A和B,就是让A的每一个字符和B的每一个字符比较,当两字符不一样时进行回退,A回到最开始匹配时的下一个字符,B回退到第一个字符。
#include#include 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]!=' ')&&(needle[j]!=' ')) if(haystack[i]==needle[j]) { i++; j++; } else { d++; i=d, j=0; } if(d 改进:因为回退的程度太大次数多所以,有一个kmp算法,这个算法的主要思路是让A字符串不回退至让B回退部分即可,难点就是就算匹配串的next数组。
#include#include 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]!=' ')&&(needle[j]!=' ')) 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]!=' ') { if(k==-1) { a[++i]=0;k=0; } else if(t[i]==t[k]) a[++i]=++k; else k=a[k]; } }



