Share my simple Sunday algorithm in C++


  • 0
    R
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int m = haystack.size(), n = needle.size();
            if (n == 0) return 0;
            vector<int> shift_table(256, n+1);
            int i, j;
            for (i = 0; i < n; ++i) 
                shift_table[needle[i]] = n-i;
            for (i = 0; i <= m-n; ) {
                for (j = 0; j < n; ++j) {
                    if (haystack[i+j] != needle[j])
                        break;
                }
                if (j == n)
                    return i;
                else 
                    i += shift_table[haystack[i+n]];
            }
            return -1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.