LeetCode OJ:Implement strStr()
2014-01-30 19:02
239 查看
Implement strStr()
Implement strStr().Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
算法思想:
循环扫描,比较直白
class Solution { public: char *strStr(char *haystack, char *needle) { int size = strlen(haystack) - strlen(needle); for (int i = 0; i <= size; i++) { bool flag = true; for (int j = 0; j < strlen(needle); j++) { if (haystack[i + j] != needle[j]) { flag = false; break; } } if (flag == true) { return &haystack[i]; } } return NULL; } };
2、简单匹配算法BF算法
class Solution { public: char *strStr(char *haystack, char *needle) { int slen = strlen(haystack); int tlen = strlen(needle); int i = 0 ,j = 0; while ( i+j < slen && j < tlen){ if ( haystack[i+j] == needle[j] ){ j ++; } else { i ++; j = 0; } } if ( j >= tlen) return &haystack[i]; else return NULL; } };
3、KMP算法
KMP算法
class Solution { public: //代码4-1 //修正后的求next数组各值的函数代码 void get_nextval(char const* ptrn, int plen, int* nextval) { int i = 0; nextval[i] = -1; int j = -1; while( i < plen-1 ) { if( j == -1 || ptrn[i] == ptrn[j] ) //循环的if部分 { ++i; ++j; if( ptrn[i] != ptrn[j] ) nextval[i] = j; else nextval[i] = nextval[j]; } else j = nextval[j]; } } char *strStr(char *haystack, char *needle) { int slen = strlen(haystack); int tlen = strlen(needle); int i = 0 ,j = 0; int *nextval=new int[tlen]; get_nextval(needle,tlen,nextval); while ( i+j < slen && j < tlen){ if ( j == -1 || haystack[i+j] == needle[j] ){ j ++; } else { i ++; j = nextval[j]; } } if ( j >= tlen) return &haystack[i]; else return NULL; } };
相关文章推荐
- [LeetCode OJ]Implement strStr()
- LeetCode OJ - Implement strStr()
- LeetCode OJ:Implement strStr()(实现子字符串查找)
- 【LeetCode OJ 28】Implement strStr()
- LeetCode OJ 28 Implement strStr() [Easy]
- LeetCode OJ 之 Implement strStr() (在字符串中查找字符串)
- LeetCode OJ--Implement strStr()
- Leetcode OJ : Implement strStr() [ Boyer–Moore string search algorithm ] python solution
- LeetCode OJ - Implement strStr()
- LeetCode—Implement strStr()
- Leetcode28 Implement strStr()
- (LeetCode)Implement strStr()
- LeetCode3.2(Implement strStr())
- LeetCode_OJ【28】Implement strStr()
- 028 - Implement strStr()
- LeetCode OJ:Implement Stack using Queues(队列实现栈)
- LeetCode OJ:Implement Trie (Prefix Tree)(实现一个字典树(前缀树))
- LeetCode 28 . Implement strStr()
- leetcode(57)- Implement strStr()
- 28. Implement strStr()