LeetCode 刷题记录28. Implement strStr()

本文详细介绍了如何使用暴力法和KMP算法实现strStr()函数,用于查找子字符串在主字符串中首次出现的位置。提供了C++、Java和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().

解法1:
暴力法
i表示开始匹配的位置,j和k分别遍历从i开始的父字符串和子字符串,如果比较结束后k == n,表示匹配完成,返回位置i
c++:

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.empty()) return 0;
        int m = haystack.size();
        int n = needle.size();
        if(n > m) return -1;
        
        for(int i = 0; i <= (m - n); i++){
            int j = i;
            int k = 0;
            while(j < m && k < n && haystack[j] == needle[k]){
                j++;
                k++;
            }
            if(k == n){
                return i;
            }
        }
        return -1;
    }
};

java:

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle.isEmpty()) return 0;
        int m = haystack.length();
        int n = needle.length();
        if(n > m) return -1;
        
        for(int i = 0; i <= (m - n); i++){
            int j = i;
            int k = 0;
            while(j < m && k < n && haystack.charAt(j) == needle.charAt(k)){
                j++;
                k++;
            }
            if(k == n){
                return i;
            }
        }
        return -1;
    }
}

Python:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle: return 0
        m = len(haystack)
        n = len(needle)
        if n > m: return -1
        
        for i in xrange(m - n + 1):
            j = i
            k = 0
            while j < m and k < n and haystack[j] == needle[k]:
                j += 1
                k += 1
            
            if k == n :
                return i
            
        
        return -1

解法2:
kmp法
从头到尾彻底理解KMP(2014年8月22日版)
KMP算法的Next数组详解
c++:

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

java:

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle == null || needle.isEmpty()) return 0;
        int m = haystack.length();
        int n = needle.length();
        if(n > m) return -1;
        char[] s = haystack.toCharArray();
        char[] p = needle.toCharArray();
        int[] next = getNext(p);
        int i = 0;
        int j = 0;
        while(i < m && j < n){
            if(j == -1 || s[i] == p[j]){
                i++;
                j++;
            } else{
                j = next[j];
            }
        }
        if(j == n){
            return i - j;
        }else {
            return -1; 
        }
    }
    public int[] getNext(char[] p){
        
        int k = -1;
        int j = 0;
        int n = p.length;
        int[] next = new int[n];
        next[0] = -1;
        while(j < n - 1){
            if(k == -1 || p[k] == p[j]){
                ++k;
                ++j;
                next[j] = k;
            } else {
                k = next[k];
            }
        }
        return next;
        
    }
}

python:

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

另外对next数组的改进

void getNext(string& needle, vector<int>& next){
        int k = -1;
        int j = 0;
        int n = needle.size();
        next[0] = -1;
        while(j < n - 1){
            if(k == -1 || needle[k] == needle[j]){
                ++k;
                ++j;
                if(needle[k] == needle[j]){
                    next[j] = next[k];
                } else {
                    next[j] = k;
                }
                
            } else {
                k = next[k];
            }
        }
        
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值