Leetcode Index

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.

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().

主要是判断特殊情况,其他直接比较就行。

class Solution {
public:
int strStr(string haystack, string needle) {
int n_len=needle.length();
int h_len=haystack.length();
if(n_len==0) return 0;
if(n_len>h_len) return -1;
if(n_len == h_len) return haystack == needle? 0:-1;
for(int i=0;i<h_len-n_len+1;i++)
if(haystack[i] == needle[0] && haystack.substr(i,n_len) == needle) return i;
return -1;
}
};

执行用时 :4 ms, 在所有 C++ 提交中击败了93.87%的用户 内存消耗 :9 MB, 在所有 C++ 提交中击败了84.51%的用户