# 28.Implement strStr()

**28.Implement strStr()**

难度:Easy

> 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().
```

主要是判断特殊情况，其他直接比较就行。

```
class Solution {
public:
    int strStr(string haystack, string needle) {
        int n_len=needle.length();
        int h_len=haystack.length();
        if(n_len==0) return 0;
        if(n_len>h_len) return -1;
        if(n_len == h_len) return haystack == needle? 0:-1;
        for(int i=0;i<h_len-n_len+1;i++)
            if(haystack[i] == needle[0] && haystack.substr(i,n_len) == needle) return i;
        return -1;
    }
};
```

> 执行用时 :4 ms, 在所有 C++ 提交中击败了93.87%的用户\
> 内存消耗 :9 MB, 在所有 C++ 提交中击败了84.51%的用户


---

# 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://dfine.gitbook.io/leetcode/28.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.
