28.Implement strStr()
28.Implement strStr()
难度:Easy
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
1
Example 1:
2
3
Input: haystack = "hello", needle = "ll"
4
Output: 2
5
Example 2:
6
7
Input: haystack = "aaaaa", needle = "bba"
8
Output: -1
9
Clarification:
10
11
What should we return when needle is an empty string? This is a great question to ask during an interview.
12
13
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().
Copied!
主要是判断特殊情况,其他直接比较就行。
1
class Solution {
2
public:
3
int strStr(string haystack, string needle) {
4
int n_len=needle.length();
5
int h_len=haystack.length();
6
if(n_len==0) return 0;
7
if(n_len>h_len) return -1;
8
if(n_len == h_len) return haystack == needle? 0:-1;
9
for(int i=0;i<h_len-n_len+1;i++)
10
if(haystack[i] == needle[0] && haystack.substr(i,n_len) == needle) return i;
11
return -1;
12
}
13
};
Copied!
执行用时 :4 ms, 在所有 C++ 提交中击败了93.87%的用户 内存消耗 :9 MB, 在所有 C++ 提交中击败了84.51%的用户
Copy link