LeetCode28. Implement strStr()(C++/Python)

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

题目大意:寻找子字符串,以下是四种方法(重要性依次增加)

方法一:暴力法

C++

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.length()==0)
            return 0;
        for(int i=0;i<haystack.size();i++){
            for(int j=0;j<needle.length();j++){
                if(i+j>=haystack.length()||haystack[i+j]!=needle[j])
                    break;
                if(j==needle.length()-1)
                    return i;
            }
        }
        return -1;
    }
};

Python

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        for i in range(0, len(haystack) - len(needle) + 1):
            if haystack[i:i+len(needle)] == needle:
                return i
        return -1

方法二:库函数find(偷懒hhhh)

C++

class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);
    }
};

Python

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

方法三(经典算法):KMP

next数组开大一点哎~~

C++

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n=haystack.length(),m=needle.length();
        if(m==0)
            return 0;
        if(n==0)
            return -1;
        vector<int>next(100005);
        next[0]=-1;
        int j=-1,i=0;
        while(i<m){
            if(j==-1||needle[j]==needle[i]){
                ++i;++j;
                next[i]=j;
            }
            else
                j=next[j];
        }
        i=0;j=0;
        while(i<n&&j<m){
            if(j==-1||haystack[i]==needle[j]){
                ++i;++j;
            }
            else
                j=next[j];
        }
        if(j==m)
            return i-j;
        else
            return -1;
    }
};

Python

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle: return 0
        if not haystack: return -1
        myNext = [0] * 100005
        myNext[0] = -1
        i, j = 0, -1
        while i < len(needle):
            if j == -1 or needle[j] == needle[i]:
                i += 1
                j += 1
                myNext[i] = j
            else:
                j = myNext[j]
        i, j = 0, 0
        while i < len(haystack) and j < len(needle):
            if j == -1 or haystack[i] == needle[j]:
                i += 1
                j += 1
            else:
                j = myNext[j]
        return i-j if j == len(needle) else -1
        

KMP算法模板

#include <iostream>
#include <string>
#include <vector>
using namespace std;
string pat,txt;
int N,M;
std::vector<int> next;
int main(){
	N=txt.length();M=pat.length();
	next.resize(M);
	getNext();
	retrun KMP();
}
void getNext(){
	next[0]=-1;
	int j=-1,i=0;
	while(i<M){
		if(j==-1||pat[j]==pat[i]){
			++i;++j;
			next[i]=j;
		}
		else
			j=next[j];
	}
}
int KMP(){
	int i=0,j=0;
	while(i<N&&j<M){
		if(j==-1||txt[i]==pat[j]){
			++i;++j;
		}
		else
			j=next[j];
	}
	if(j==M)
		return i-j;
	else
		return -1;
}

方法四(经典算法):Byore Moore(比KMP算法快很多)

C++

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n=haystack.length(),m=needle.length(),skip;
        vector<int>Right(256,-1);
        for(int i=0;i<m;i++)
            Right[needle[i]]=i;
        for(int i=0;i<=n-m;i+=skip){
            skip=0;
            for(int j=m-1;j>=0;--j){
                if(needle[j]!=haystack[i+j]){
                    skip=j-Right[haystack[i+j]];
                    if(skip<1)
                        skip=1;
                    break;
                }
            }
            if(skip==0)
                return i;
        }
        return -1;
    }
};

Python

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        m, n, skip = len(needle), len(haystack), 0
        Right = [-1] * 256
        for i in range(m):
            Right[ord(needle[i])] = i
        i = 0
        while i <= n - m:
            skip = 0
            for j in range(m-1, -1, -1):
                if needle[j] != haystack[i+j]:
                    skip = j - Right[ord(haystack[i+j])]
                    if skip < 1:
                        skip = 1
                    break
            if not skip: return i
            i += skip
        return -1

Byore Moore算法模板

#include <iostream>
#include <vector>
#include <string>
using namespace std;
string pat,txt;
int R=256,M,N,skip;
std::vector<int> right(256,-1);
int BoyerMoore (){
	M=pat.length();N=txt.length();
	for(int i=0;i<M;i++)
		right[pat[i]]=i;
	for(int i=0;i<=N-M;i+=skip){
		skip=0;
		for(int j=M-1;j>=0;j--)
			if(pat[j]!=txt[i+j]){
				skip=j-right[txt[i+j]];
				if(skip<1)
					skip=1;
				break;
			}
		if(skip==0)
			return i;
	}
	return -1;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值