首页 > 代码库 > Implement strStr()
Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路:使用DFS即可。
1 class Solution { 2 public: 3 char *strStr( char *haystack, char *needle ) { 4 int hlen = strlen( haystack ), nlen = strlen( needle ); 5 for( int i = 0; i <= hlen-nlen; ++i ) { 6 int j = 0; 7 for( ; j < nlen; ++j ) { 8 if( haystack[i+j] != needle[j] ) { break; } 9 }10 if( j == nlen ) { return haystack+i; }11 }12 return 0;13 }14 };
KMP算法,预先计算needle的跳转信息。
1 class Solution { 2 public: 3 char *strStr( char *haystack, char *needle ) { 4 int hlen = strlen( haystack ), nlen = strlen( needle ); 5 if( nlen == 0 ) { return haystack; } 6 vector<int> jump; 7 GetJumpTable( needle, nlen, jump ); 8 int i = 0, j = 0; 9 while( i <= hlen-nlen ) {10 if( haystack[i+j] != needle[j] ) {11 if( j == 0 ) {12 ++i;13 } else {14 i += j-1 - jump[j-1];15 j = jump[j-1]+1;16 }17 } else {18 ++j;19 if( j == nlen ) { return haystack+i; }20 }21 }22 return 0;23 }24 private:25 void GetJumpTable( const char *needle, int nlen, vector<int> &jump ) {26 jump.resize( nlen, -1 );27 for( int i = 1; i <= nlen; ++i ) {28 int k = i-1;29 while( k != -1 ) {30 k = jump[k];31 if( needle[k+1] == needle[i] ) {32 jump[i] = k+1;33 break;34 }35 }36 }37 return;38 }39 };
Implement strStr()
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。