天天看點

LeetCode | 28. Implement strStr()Description

Description

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

Brute Force | 一步步來

要把情況考慮周全可不是個簡單事~但是可喜可賀,第一次答案比98.94%快:)繼續加油!

LeetCode | 28. Implement strStr()Description
class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle == "") {
            //empty string
            return 0;
        }
        
        if (needle.size() > haystack.size()) {
            return -1;
        }
        
        bool isSame = false;
        int j = 0;
        int set = -1;
        
        for (int i = 0; i < haystack.size(); i++) {
            if (haystack[i] == needle[j] && !isSame) {
                //first time the same
                set = i;
                // cout <<"set: "<< set<<endl;
                j++;
                isSame = true;
                
            } else if (isSame && haystack[i] == needle[j]) {
                //continuation of the same thing
                j++;
                
            } else if (isSame && haystack[i] != needle[j]) {
                //previously the same, but not now
                i -= j;
                j = 0;
                isSame = false;
                
            }
            
            if (j >= needle.size()) {
                return set;
            }
            if (haystack.size() - i <= needle.size() - j) {
                return -1;
            }
        }
        
        return set;
    }
};