Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:
1、暴力法。逐一匹配,然后回溯。代码如下,但是产生超时错误。
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.length();
int len2=needle.length();
if(len2>len1){
return -1;
}
for(int i=0; i
2、KMP算法。
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.length();
int len2=needle.length();
if(len2>len1){
return -1;
}
if(len2==0){
return 0;
}
int next[len2];
next[0]=-1;
int i=0, j=-1;
while(i
二次刷题(update in 2015-07-31)
1、同样的暴力法,这次竟然很快的过了,看来编码规范还是非常重要的:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length();
int n = needle.length();
if(m
KMP算法老是不懂,next数组的求法需要着重记一下。参考博客:http://blog.csdn.net/v_july_v/article/details/7041827
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length();
int n = needle.length();
if(m
转载请注明: » [LeetCode] Implement strStr()
<!--
-->
原文作者:;如有侵权,请联系管理员删除。