Implement strStr() Problem Solution

Implement strStr() Problem: Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = “sadbutsad”, needle = “sad” Output: 0 Explanation: “sad” occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = “leetcode”, needle = “leeto” Output: -1 Explanation: “leeto” did not occur in “leetcode”, so we return -1.

Implement strStr() Problem Solution

Problem Solution In Python

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        try:
            return 0 if len(needle) == 0 else haystack.index(needle, 0, len(haystack))
        except:
            return -1

Problem Solution In Java

class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
 }
}

Problem Solution In C++

class Solution {
public:
    int strStr(string haystack, string needle) 
    {
        if(needle==" ")
            return 0;
        if(haystack.find(needle)!=string::npos)
            return haystack.find(needle);
        return -1;
    }
};

Problem Solution In C

int strStr(char * haystack, char * needle)
{
    int len = strlen(haystack),j;
    int l=strlen(needle);
   
    if(l==0)
    return 0;
    
    if(len<l)
    return -1;
    
    for(int i=0;i<len;i++)
    {
        for(j=0;j<l;j++)
        {
            if(haystack[i+j]!=needle[j])
            break;    
        }
        if(j==l)
        return i;
    }  
    return -1;
}

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment