題目鏈接
tag:
- Easy;
question:
??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().
思路:
??這道題讓我們在一個字符串中找另一個字符串第一次出現(xiàn)的位置披粟,那我們首先要做一些判斷咒锻,如果子字符串為空,則返回0守屉,如果子字符串長度大于母字符串長度惑艇,則返回-1。然后我們開始遍歷母字符串拇泛,我們并不需要遍歷整個母字符串滨巴,而是遍歷到剩下的長度和子字符串相等的位置即可,這樣可以提高運(yùn)算效率碰镜。然后對于每一個字符兢卵,我們都遍歷一遍子字符串,一個一個字符的對應(yīng)比較绪颖,如果對應(yīng)位置有不等的秽荤,則跳出循環(huán),如果一直都沒有跳出循環(huán)柠横,則說明子字符串出現(xiàn)了窃款,則返回起始位置即可,代碼如下:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return 0;
int n = haystack.size(), m = needle.size();
if (n < m) return -1;
for (int i=0; i<=n-m; ++i) {
int j = 0;
for (j=0; j<m; ++j) {
if (haystack[i+j] != needle[j])
break;
}
if (j == m)
return i;
}
return -1;
}
};