# Implement strStr()

{% embed url="<https://leetcode.com/problems/implement-strstr/>" %}

## Solution 1

```go
func strStr(haystack string, needle string) int {
    ln, lh := len(needle), len(haystack)
    if ln == 0 {
        return 0
    }
    if ln > lh {
        return -1
    }
    for i,_ := range haystack {
        if haystack[i] == needle[0] && i+ln <= lh && haystack[i+ln-1] == needle[ln-1] {
            if haystack[i:i+ln] == needle {
                return i
            }
        }
    }
    return -1
}
```

## Solution 2

```go
func strStr(haystack string, needle string) int {
    for i := 0; ; i++ {
        for j := 0; ; j++ {
            if j == len(needle) {
                return i
            }
            if i+j == len(haystack) {
                return -1
            }
            if needle[j] != haystack[i+j] {
                break
            }
        }
    }
}

// haystack = "hello", needle = "ll"
// i: 0 1 2 2 2
// j: 0 0 0 1 2
```

## Solution 3

```go
import "strings"

func strStr(haystack string, needle string) int {
    return strings.Index(haystack, needle)
}
```

{% hint style="info" %}
Not really a "solution"...
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.yushunchen.com/algo/string/implement-strstr.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
