Short KMP C++ solution


  • 0
    B
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            string s=" "+needle+"#"+haystack;
            if (needle.size()==0) {
                return 0;
            }
            if (haystack.size()==0) {
                return -1;
            }
            vector<int> p(s.size()+1,0);
            int t=0;
            for (int i=2; i<=s.size(); i++) {
                while (s[t+1]!=s[i] && t>0) {
                    t=p[t];
                }
                if (s[t+1]==s[i]) {
                    t++;
                }
                p[i] = t;
                if (p[i]==needle.size()) {
                    return i-(2*needle.size())-1;
                }
            }
            return -1;
        }
    };
    

Log in to reply
 

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