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().
這道題讓我們在一個字符串中找另一個字符串第一次出現的位置,那首先要做一些判斷,如果子字符串為空,則返回0,如果子字符串長度大於母字符串長度,則返回 -1。然后開始遍歷母字符串,這里並不需要遍歷整個母字符串,而是遍歷到剩下的長度和子字符串相等的位置即可,這樣可以提高運算效率。然后對於每一個字符,都遍歷一遍子字符串,一個一個字符的對應比較,如果對應位置有不等的,則跳出循環,如果一直都沒有跳出循環,則說明子字符串出現了,則返回起始位置即可,代碼如下:
class Solution { public: int strStr(string haystack, string needle) { if (needle.empty()) return 0; int m = haystack.size(), n = needle.size(); if (m < n) return -1; for (int i = 0; i <= m - n; ++i) { int j = 0; for (j = 0; j < n; ++j) { if (haystack[i + j] != needle[j]) break; } if (j == n) return i; } return -1; } };
我們也可以寫的更加簡潔一些,開頭直接套兩個 for 循環,不寫終止條件,然后判斷假如j到達 needle 的末尾了,此時返回i;若此時 i+j 到達 haystack 的長度了,返回 -1;否則若當前對應的字符不匹配,直接跳出當前循環,參見代碼如下:
解法二:
class Solution { public: int strStr(string haystack, string needle) { for (int i = 0; ; ++i) { for (int j = 0; ; ++j) { if (j == needle.size()) return i; if (i + j == haystack.size()) return -1; if (needle[j] != haystack[i + j]) break; } } return -1; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/28
類似題目:
參考資料:
https://leetcode.com/problems/implement-strstr/
https://leetcode.com/problems/implement-strstr/discuss/12807/Elegant-Java-solution
https://leetcode.com/problems/implement-strstr/discuss/12956/C%2B%2B-Brute-Force-and-KMP