28.实现 strStr()
题目链接:力扣
看到题目的第一想法:
KMP算法对于现在的我来说还是有一定难度的,看了好久题解才勉强看明白,其中有些地方现在还是没有太搞懂为什么是这样,以后还得多看看才能逐渐熟悉和懂得为什么要这样
class Solution { public: void getNext(int* next, string needle) { // 初始化 int j = 0; next[0] = j; for(int i = 1; i < needle.size(); i++) { // 前后缀不相同: while(j >= 1 && needle[j+1] != needle[i]) { j = next[j]; } // 前后缀相同 if(needle[i] == needle[j]) { j++; } next[i] = j; } } int strStr(string haystack, string needle) { if(needle.size() == 0) return 0; // 这道题要使用KMP算法,实现next数组就为前缀表的情况 int next[needle.size()]; getNext(next,needle); for(int i = 0; i < needle.size(); i++) { printf("%d ", next[i]); } printf("\n\n"); int j = 0; for(int i = 0; i < haystack.size(); i++) { // next和neddle不匹配 printf("%c %c %d\n",needle[j+1],haystack[i],j); while(j >= 1 && needle[j] != haystack[i]) { j = next[j]; } printf("%c %c %d",needle[j+1],haystack[i],j); // next和neddle相等的情况 if(needle[j+1] == haystack[i]) { j++; } printf("\n%c %c %d\n\n",needle[j+1],haystack[i],j); // 若已经找到子串 if(j == (needle.size()-1)) return (i-needle.size()+1); } return -1; } };
遇到的困难:
对这个算法还没有彻底熟悉,在写的时候只是把怎么写记住了,还没明白其中的具体原理,KMP算法还是很妙的,对于程序运行时间的提升非常大
459.重复的子字符串
看到题目的第一想法:
第一眼看这道题还是非常复杂,用暴力的话只能取一小段看能不能实现重复,这样时间复杂度明显特别高,一眼还是没有明白为什么要用KMP算法,还是对next数组的具体意义不太懂,明天再看看吧
class Solution { public: void getNext (int* next, const string& s){ next[0] = -1; int j = -1; for(int i = 1;i < s.size(); i++){ while(j >= 0 && s[i] != s[j + 1]) { j = next[j]; } if(s[i] == s[j + 1]) { j++; } next[i] = j; } } bool repeatedSubstringPattern (string s) { if (s.size() == 0) { return false; } int next[s.size()]; getNext(next, s); int len = s.size(); if (next[len - 1] != -1 && len % (len - (next[len - 1] + 1)) == 0) { return true; } return false; } };
遇到的困难:
没弄懂next数组的具体含义,不晓得为什么要这样写,但这样真的好简洁啊~
总结:
字符串这一章也顺利完结了,除了KMP算法其他都完成的还不错,KMP属实是有点难了,任重而道远啊~~