暴力算法就不写了,没什么意义,总得来说就是通过寻找首个字符串中与第二个字符串首字符一致的字符,然后进行判断。代码也不贴了
真正重要的是KMP算法,非常巧妙,通过利用已经匹配到的字符来实现,中心思想就是某个字符串的相同的前缀与后缀,具体细节不详细描述了,贴代码
class Solution { public: int strStr(string haystack, string needle) { if(haystack.length()<needle.length()) return -1; else if(needle.length() == 0) return 0; int* next = new int[needle.length()]; next[0] = -1; for(int i = 1 ; i < needle.length() ; i++) { int f = next[i-1]; while(needle[f+1]!=needle[i] && f>=0) f = next[f]; if(needle[f+1] == needle[i]) next[i] = f+1; else next[i] = -1; } int i = 0; int j = 0; while(i<haystack.length()) { if(haystack[i] == needle[j]) { i++; j++; if(j == needle.length()) return i-needle.length(); } else { if(j == 0) i++; else j = next[j-1]+1; } } return -1; } };
想复习的时候就看看这个:https://www.cnblogs.com/SYCstudio/p/7194315.html
原文:https://www.cnblogs.com/zhaohhhh/p/14529231.html