My C++ solution 3ms, beats 100%


  • 0
    C
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            if(needle.empty()) return 0;
            const int StrLen = haystack.length();
            const int PatLen = needle.length();
            if(PatLen > StrLen) return -1;
            const int N = StrLen - PatLen + 1;
            for(int i = 0; i < N; i++){
                for(int k = 0; k < PatLen; k++){
                    if(haystack[i + k] != needle[k])
                        break;
                    if(k == PatLen - 1)
                        return i;
                }
            }
            return -1;
        }
    };
    

Log in to reply
 

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