958 B
958 B
layout, title, last_solved, category, leetcode_url, status
| layout | title | last_solved | category | leetcode_url | status |
|---|---|---|---|---|---|
| page | Implement strstr | string | https://leetcode.com/problems/implement-strstr | Attempted |
Problem
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
Solution
{% highlight python %}
def strStr(self, haystack: str, needle: str) -> int:
# "hello" "ll"
if not needle: return 0
for i in range(len(haystack)):
if haystack[i]==needle[0]:
substr = haystack[i:i+len(needle)]
if substr==needle:
return i
return -1
{% endhighlight %}