LeetCode 28 Implement strStr() (C,C++,Java,Python)

Problem:

Implement strStr().

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

Update (2014-11-02):

The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char
*
 or String, please click the reload button  to
reset your code definition.

Solution:

O(nm) runtime, O(1) space – Brute force:

You could demonstrate to your interviewer that this problem can be solved using known efficient algorithms such as Rabin-Karp algorithm, KMP algorithm, and the Boyer- Moore algorithm. Since these algorithms are usually studied in an advanced algorithms class,
it is sufficient to solve it using the most direct method in an interview – The brute force method.

The brute force method is straightforward to implement. We scan the needle with the haystack from its first position and start matching all subsequent letters one by one. If one of the letters does not match, we start over again with the next position in the
haystack.

The key is to implement the solution cleanly without dealing with each edge case separately.

经典的KMP应用,暴力什么的还是不要提了,参考这里:从头到尾彻底理解KMP

题目大意:

给两个字符串,求第二个字符串在第一个字符串中出现的最小位置,如果没有出现则输出-1

Java源代码(323ms):

public class Solution {
    public int strStr(String haystack, String needle) {
        char[] chs1=haystack.toCharArray();
        char[] chs2=needle.toCharArray();
        int len1=chs1.length,len2=chs2.length;
        int[] next=new int[len2+1];
        getNext(chs2,next,len2);
        int i=0,j=0;
        while(i<len1 && j<len2){
            if(j==-1 || chs1[i]==chs2[j]){
                i++;j++;
            }else{
                j=next[j];
            }
        }
        if(j<len2)return -1;
        return i-len2;
    }
    private void getNext(char[] chs,int[] next,int len){
        int i=0,j=-1;
        next[0]=-1;
        while(i<len){
            if(j==-1 || chs[i]==chs[j]){
                i++;j++;
                next[i]=j;
            }else{
                j=next[j];
            }
        }
    }
}

C语言源代码(2ms):

void getNext(char *needle,int* next){
    int i=0,j=-1;
    next[0]=-1;
    while(needle[i]){
        if(j==-1 || needle[j]==needle[i]){
            j++;
            i++;
            next[i]=j;
        }else{
            j=next[j];
        }
    }
}
int strStr(char* haystack, char* needle) {
    int length=strlen(needle),i=0,j=0;
    int *next=(int*)malloc(sizeof(int)*(length+1));
    getNext(needle,next);
    while(j==-1 || (haystack[i] && needle[j])){
        if(j==-1 || haystack[i]==needle[j]){
            j++;i++;
        }else{
            j=next[j];
        }
    }
    if(needle[j])return -1;
    else return i-length;
}

C++源代码(8ms):

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1=haystack.size(),len2=needle.size();
        int* next=(int*)malloc(sizeof(int)*(len2+1));
        getNext(needle,next,len2);
        int i=0,j=0;
        while(i<len1 && j<len2){
            if(j==-1 || haystack[i]==needle[j]){
                i++;j++;
            }else{
                j=next[j];
            }
        }
        if(j<len2)return -1;
        else return i-len2;
    }
private:
    void getNext(string needle,int* next,int len1){
        int i=0,j=-1;
        next[0]=-1;
        while(i<len1){
            if(j==-1 || needle[i]==needle[j]){
                j++;i++;
                next[i]=j;
            }else{
                j=next[j];
            }
        }
    }
};

Python源代码(74ms):

class Solution:
    # @param {string} haystack
    # @param {string} needle
    # @return {integer}
    def strStr(self, haystack, needle):
        len1=len(haystack);len2=len(needle)
        next=[-1 for i in range(len2+1)]
        self.getNext(needle,next,len2)
        i=0;j=0
        while i<len1 and j<len2:
            if j==-1 or haystack[i]==needle[j]:
                i+=1;j+=1
            else:j=next[j]
        if j<len2:return -1
        else:return i-len2
    def getNext(self,needle,next,len2):
        i=0;j=-1
        while i<len2:
            if j==-1 or needle[i]==needle[j]:
                i+=1
                j+=1
                next[i]=j
            else:j=next[j]

时间: 2024-08-06 16:00:55

LeetCode 28 Implement strStr() (C,C++,Java,Python)的相关文章

44. leetcode 28. Implement strStr()

28. Implement strStr() Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 思路:子串匹配,朴素匹配.

leetCode 28. Implement strStr() 字符串

28. Implement strStr() Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 在haystack中找与needle 第一个相匹配的位置.如果找不到,返回-1. 代码如下: class Solution { public:     int strStr(string haystac

Java [leetcode 28]Implement strStr()

题目描述: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Update (2014-11-02): The signature of the function had been updated to return the index instead of the pointer. If you

LeetCode 28. Implement strStr()

https://leetcode.com/problems/implement-strstr/ Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 字符串简单题.一定要写的没BUG. 如果不在函数最后一行写return语句的话,LeetCode会出RUNTIME ERROR. Line 27: co

19.1.30 [LeetCode 28] Implement strStr()

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",

[LeetCode] 28. Implement strStr() 实现strStr()函数

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",

[LeetCode] 28. Implement strStr() ☆

Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 解法: 这道题让我们在一个字符串中找另一个字符串第一次出现的位置,那我们首先要做一些判断,如果子字符串为空,则返回0,如果子字符串长度大于母字符串长度,则返回-1.然后我们开始遍历母字符串,我们并不需要遍历整个母字符串,而是遍历到剩下的长度和子字符

LeetCode 28 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 思路: 通过最简单的BF遍历,如果不符合则指向下一个字符,最后如果长度等于子串长度,则返回位置. 代码: public static int strStr(String haysta

leetcode 28. Implement strStr() 实现strStr()

C++代码,题目相对不是很难 1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 if(needle.empty()) return 0; 5 int m=haystack.size(),n=needle.size(); 6 int flag=-1; 7 for(int i=0;i<=m-n;i++){ 8 if(haystack[i]==needle[0]){ 9 flag=i; 10 fo