🌐
Red Quark
redquark.org › leetcode › 0028-implement-strstr
LeetCode #28 - Implement StrStr | Red Quark
public class ImplementStrStr { public int strStr(String haystack, String needle) { // Base condition if (haystack == null || needle == null) { return -1; } // Special case if (haystack.equals(needle)) { return 0; } // length of the needle int needleLength = needle.length(); // Loop through the haystack and slide the window for (int i = 0; i < haystack.length() - needleLength + 1; i++) { // Check if the substring equals to the needle if (haystack.substring(i, i + needleLength).equals(needle)) { return i; } } return -1; } }
🌐
LeetCode
leetcode.com › problems › find-the-index-of-the-first-occurrence-in-a-string › solutions › 1326344 › c-implement-strstr-solution
Implement strStr() Solution - Find the Index of the First ...
Find the Index of the First Occurrence in a String - 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.
🌐
Codeewander
codeewander.github.io › leetcode 28 - implement strstr()
LeetCode 28 - Implement strStr() | Kira Yang
/** * @param {string} haystack * @param {string} needle * @return {number} */ var strStr = function (haystack, needle) { const len = needle.length; if (len === 0) return 0; for (let i = 0; i < haystack.length; i++) { if (haystack.substring(i, i + len) === needle) { return i; } } return -1; };
🌐
Gitbook
aaronice.gitbook.io › lintcode › string › implement-strstr
Implement strStr() | LintCode & LeetCode
public class Solution { /** * @param source: * @param target: * @return: return the index */ public int strStr(String source, String target) { // Write your code here if (target.equals("")){ return 0; } for (int i = 0; i < source.length() - target.length() + 1; i++){ int j = 0; int k = i; while (j < target.length() && k < source.length()){ if (source.charAt(k) == target.charAt(j)){ k++; j++; } else { break; } } if(j == target.length()){ return k - target.length(); } } return -1; } }
🌐
Alkesh blogs
alkeshghorpade.me › post › leetcode-implement-strstr
LeetCode - Implement strStr()
We can solve the problem using recursive approach as below: int strStr(string haystack, string needle) { // ...basic condition check code for (int i = 0; i < haystack.length(); i++){ if (haystack.charAt(i) == needle.charAt(0)) { String s = strStr(haystack.substring(i + 1), needle.substring(1)); ...
🌐
GitBooks
cheonhyangzhang.gitbooks.io › leetcode-solutions › content › 28_implement_strstr__easy.html
28 Implement strStr() – Easy · LeetCode solutions
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Very straightforward. String manipulation. public class Solution { public int strStr(String haystack, String needle) { if (needle.equals("")) { return 0; } for (int ...
🌐
Leetcode
articles.leetcode.com › implement-strstr-to-find-substring-in
Implement strstr() to Find a Substring in a String – LeetCode
When you are comparing each character of the two strings via: while (*p1 && *p2 && *p1 == *p2) { p1++; p2++; } you can record the next character that equals *target. Then if this comparison doesn’t give a match, you can start directly from the next location instead of doing p1 = p1Begin + ...
🌐
Medium
medium.com › @edwardllookk › day-9-implement-strstr-c-solution-41a255b1b05d
Day 9: Implement strStr() — C++ solution | by Ed | Medium
January 15, 2019 - class Solution { public: int strStr(string haystack, string needle) {int h_sz = haystack.size(); int n_sz = needle.size(); if (!n_sz) { return 0; } for (int i = 0; i < h_sz; i ++) { if (haystack[i] == needle[0]) { int j = 0; for (; j < n_sz; j++) { if (haystack[i+j] != needle[j]) break; } if (j == n_sz) return i; } } return -1; } };
Find elsewhere
🌐
Beizhedenglong
beizhedenglong.github.io › leetcode-solutions › docs › implement-strstr
Implement strStr() · LeetCode Site Generator
/** Rabin-Karp * @param {string} haystack * @param {string} needle * @return {number} */ const strStr = function (haystack, needle) { const base = 256 const prime = 1439173969 if (needle === '') { return 0 } let hashNeedle = 0 const magic = (base ** (needle.length - 1)) % prime const product = prime * base for (const c of needle) { hashNeedle = (hashNeedle * base + c.charCodeAt(0)) % prime } const isEqual = i => needle === haystack.slice(i, i + needle.length) let hash = 0 for (let i = 0; i <= haystack.length - needle.length; i++) { if (i === 0) { for (let j = 0; j < needle.length; j++) { hash = (hash * base + haystack[j].charCodeAt(0)) % prime } } else { hash = (hash - haystack[i - 1].charCodeAt(0) * magic + product) % prime hash = (hash * base + haystack[i + needle.length - 1].charCodeAt(0)) % prime } if (hash === hashNeedle && isEqual(i)) { return i } } return -1 }
🌐
Eugenejw
eugenejw.github.io › 2017 › 07 › leetcode-28
Weihan's Coding Blog | Implement strStr method (leetcode 28)
Note: the runtime looks okay just because leetcode’s unit test cases are simple. class Solution(object): def strStr(self, haystack, needle): """ :Find the substring in a brutal way. :type haystack: str :type needle: str :rtype: int """ h, n = haystack, needle N = len(h) M = len(n) if M == 0: # edge case, when needle is "".
🌐
Codesays
codesays.com › 2014 › solution-to-implement-strstr-by-leetcode
Solution to Implement strStr() by LeetCode – Code Says
C code. C code run. Run code run… please · Question: http://oj.leetcode.com/problems/implement-strstr/
🌐
Medium
lenchen.medium.com › leetcode-28-implement-strstr-64de75d9ffb1
LeetCode #28 Implement strStr(). Easy (not that easy actually) | by Len Chen | Medium
September 17, 2018 - Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. ... What should we return when needle is an empty string?
🌐
LeetCode
leetcode.ca › all › 28.html
Leetcode 28. Implement strStr()
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(). ... All contents and pictures on this website come from the Internet and are updated regularly every week. They are for personal study and research only, and should not be used for commercial purposes.
🌐
Stack Overflow
stackoverflow.com › questions › 72795129 › leetcode-28-implement-strstr-why-my-code-failed
debugging - Leetcode 28. Implement strStr() -- Why my code failed? - Stack Overflow
class Solution { public int strStr(String haystack, String needle) { if (needle.length() == 0) { return 0; } String result = ""; int i = 0; int j = 0; while (i < haystack.length() && j < needle.length()) { if (haystack.charAt(i) == needle.charAt(j)) { result += needle.charAt(j); i++; j++; } else { result = ""; i++; } } if (result.equals(needle)) { return i - needle.length(); } return -1; }
🌐
Programmingoneonone
programmingoneonone.com › home › leetcode implement strstr() problem solution
Leetcode Implement strStr() problem solution
July 31, 2024 - In this Leetcode Implement strStr() problem solution Implement strStr(). Return the index of the first occurrence of needle in a haystack, or -1 if the needle is not part of the haystack. class Solution: def strStr(self, haystack: str, needle: ...
Top answer
1 of 2
3

The function has several drawbacks.

For starters it should be declared like

std::string::size_type strStr( const std::string &haystack, const std::string &needle );

and if the second string is not found in the first string the function should return std::string::npos as all similar member functions of the class std::string do.

The function parameters shell be of constant referenced types.

The condition in this if-statement

if (haystack.empty() && !needle.empty())

has a redundant operand. It could be rewritten like

if (haystack.empty())

This loop

for (i; i < haystack.length(); i++) 

should stop its iterations when the size of the tail of the first string is less than the size of the second string.

in this if-statement

if (haystack[i++] != needle[j]) {

the variable i is incremented that results in incrementing the variable two times: one in this statement and the second time in the loop.

The second pair of these statements

        if (j == needle.length()) {
        return ans;

is redundant.

The function can be written the following way as it is shown in the demonstrative program.

#include <iostream>
#include <string>

std::string::size_type strStr( const std::string &haystack, const std::string &needle )
{
    if ( needle.empty() )
    {
        return 0;
    }
    else if ( haystack.empty() )
    {
        return -std::string::npos;
    }
    else
    {
        std::string::size_type ans = std::string::npos;

        auto n1 = haystack.length();
        auto n2 = needle.length();

        for ( std::string::size_type i = 0; ans == std::string::npos && i + n2 <= n1; i++ )
        {
            std::string::size_type j = 0;
            while ( j < n2 && haystack[i+j] == needle[j] ) j++;

            if ( j == n2 ) ans = i;
        }

        return ans;
    }
}

int main() 
{
    std::string haystack( "mississippi" );
    std::string needle( "issip" );

    std::cout << strStr( haystack, needle ) << '\n';

    return 0;
}

Its output is

4

2 of 2
2

The problem is that you modify i in

if (haystack[i++] != needle[j]) {

Thus preventing a second potential match from being explored. Try

if (haystack[i + j] != needle[j]) {

and fix any knock-on issues. I expect it to work as-is, though.

🌐
Medium
medium.com › nerd-for-tech › leetcode-implement-strstr-9b0499ecfd88
LeetCode — Implement strStr(). Problem statement | by Alkesh Ghorpade | Nerd For Tech | Medium
July 19, 2021 - We can solve the problem using recursive approach as below: int strStr(string haystack, string needle) { // ...basic condition check code for (int i = 0; i < haystack.length(); i++){ if (haystack.charAt(i) == needle.charAt(0)) { String s = ...
🌐
GeeksforGeeks
geeksforgeeks.org › problems › implement-strstr › 1
Implement strstr | Practice | GeeksforGeeks
Given two strings txt and pat, return the 0-based index of the first occurrence of the substring pat in txt. If pat is not found, return -1.Note: You are not allowed to use the inbuilt function. Examples : Input: txt = "GeeksForGeeks", pat = "Fr