--- title: 'LeetCode 28. Implement strStr()' disqus: hackmd --- # LeetCode 28. Implement strStr() ## Description Implement strStr(). 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. 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(). ## Example Input: haystack = "hello", needle = "ll" Output: 2 Input: haystack = "aaaaa", needle = "bba" Output: -1 ## Constraints 1 <= haystack.length, needle.length <= 104 haystack and needle consist of only lowercase English characters. ## Answer 此題可用雙層for求解,外層將haystack一個一個做平移檢查,內曾找符合needle字元的項目,若有跑到needle最後一個字元就值接return i。而第11行的return是當needle為空時就return 0,若不為空且跑到這行就表示完全不符合即return -1。 ```Cin= //2022_03_29 int strStr(char * haystack, char * needle){ int i = 0, j = 0, lh = strlen(haystack), ln = strlen(needle); for(i = 0; i <= lh - ln; i++){ for(j = 0; j < ln; j++){ if(haystack[i + j] != needle[j]){break;} if(j == ln - 1){return i;} } } return ln == 0 ? 0 : -1; } ``` ## Link https://leetcode.com/problems/implement-strstr/ ###### tags: `Leetcode`