28_Implement strStr()
[Easy]
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: 2Example 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1Example 3 (need to pay attention)
Input: haystack = "hello", needle = ""
Output: 0Example 4 (need to pay attention)
Input: haystack = "", needle = "ll"
Output: -1Example 5 (need to pay attention)
Input: haystack = "", needle = ""
Output: 0Example 6 (need to pay attention)
Input: haystack = "a", needle = "abc"
Output: -1Solution 1: Sliding Window 滑动窗口
Idea:
This is a clean brute-force algorithm. We can traverse all the possible starting points of
haystack(from0to
haystack.length() - needle.length()) and see if the following characters in haystackmatch those of needle.
Special cases:
Both
haystackandneedlecan be empty. Ifhaystackis empty,needleis not, should return-1. Ifneedleis empty,haystackis not, should return0. If both empty, should return0.
Time complexity: , where k is the number of characters in needle.
Code 1:
Code 2:
Last updated
Was this helpful?