标签:style blog http color os io ar strong for
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
在文本串中查找模式串第一次出现的位置
个人思路:
1,暴力搜索,从文本串的第一个字符开始,逐个和模式串进行匹配,若其中某个字符不匹配,则从文本串的第二个字符开始,继续上述过程,直到模式串完全匹配或者查找不到该模式串
2,kmp算法,这个算法我之前真是摸不着头脑,借着这个题目,又仔细看了一些文章理解了一遍,目前清楚了一些,以后再回过头来反复看,直到彻底消化,关于这个算法网上有很多解释,我这里给个我觉得比较好理解的一篇文章:http://billhoo.blog.51cto.com/2337751/411486,根据这篇文章的思路,我写了一个kmp算法的代码实现
暴力搜索代码:
1 #include<string.h> 2 3 class Solution { 4 public: 5 char *strStr(char *haystack, char *needle) { 6 if (!haystack || !needle) 7 { 8 return nullptr; 9 } 10 11 char *p1 = haystack; 12 char *p2 = needle; 13 int len1 = strlen(haystack); 14 int len2 = strlen(needle); 15 int flag; 16 17 while (len2 <= len1) 18 { 19 flag = true; 20 for (int i1 = 0, i2 = 0; i2 < len2; ++i1, ++i2) 21 { 22 if (p1[i1] != p2[i2]) 23 { 24 flag = false; 25 break; 26 } 27 } 28 if (flag) 29 { 30 return p1; 31 } 32 else 33 { 34 ++p1; 35 --len1; 36 } 37 } 38 39 return nullptr; 40 } 41 };
kmp代码:
1 #include<string.h> 2 3 class Solution { 4 public: 5 char *strStr(char *haystack, char *needle) { 6 if (!haystack || !needle) 7 { 8 return nullptr; 9 } 10 11 int *next = new int[strlen(needle)]; 12 13 kmp(needle, next); //计算好next数组 14 15 int needleLen = strlen(needle); 16 int i = 0, j = 0; 17 18 while (needleLen <= strlen(&haystack[i])) 19 { 20 for (; j < needleLen; ++j) 21 { 22 if (haystack[i + j] != needle[j]) 23 { 24 if (j == 0) 25 { 26 ++i; 27 break; 28 } 29 30 i += j - next[j]; 31 j = next[j]; 32 break; 33 } 34 } 35 if (j == needleLen) 36 { 37 break; 38 } 39 } 40 41 delete[] next; 42 43 if (j == needleLen) 44 { 45 return &haystack[i]; 46 } 47 else 48 { 49 return nullptr; 50 } 51 } 52 53 void kmp(char *needle, int *next) 54 { 55 int len = strlen(needle); 56 int maxPrefix = 0; 57 next[1] = 0; 58 59 for (int i = 2; i < len; ++i) 60 { 61 while (maxPrefix > 0 && needle[maxPrefix] != needle[i - 1]) 62 { 63 maxPrefix = next[maxPrefix]; 64 } 65 if (needle[maxPrefix] == needle[i - 1]) 66 { 67 ++maxPrefix; 68 } 69 next[i] = maxPrefix; 70 } 71 } 72 };
标签:style blog http color os io ar strong for
原文地址:http://www.cnblogs.com/laihaiteng/p/3961361.html