LeetCode 28 — Implement strStr()(實現strStr())
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().
翻譯
實現 strStr() 函式。
給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = “hello”, needle = “ll”
輸出: 2
示例 2:
輸入: haystack = “aaaaa”, needle = “bba”
輸出: -1
說明:
當 needle 是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle 是空字串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。
分析
剪枝優化,在haystack裡找到和needle首字母相同的字元,再以此為起始去擷取相同長度的字串,判斷是否相等。
c++實現
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "")
return 0;
int len = needle.length();
bool find = false;
int index;
for (int i = 0; i < haystack. length(); i++)
{
if (haystack[i] == needle[0])
{
string tmp = haystack.substr(i,len);
if (tmp == needle)
{
index = i;
find = true;
break;
}
}
}
if (find)
return index;
return -1;
}
};