Code gets accepts with 7ms, but is it efficient if we use in-built hash

  • 0
    This code got accepted with 7ms time. But is it efficient? I have used in-built C++ hash. In theory it should not get accepted because the hash is being re-calculated all over again during the pattern slide. Ideally I think the hash needs to be updated. But with this, the code looks smaller and easier.
    class Solution {
        int strStr(string haystack, string needle) {
            hash<string> hash_t;
            int m = haystack.length();
            int n = needle.length();
            int i = 0;
            if(n == 0 && m == 0){
                return 0;
            for(i = 0;i <= m - n;i++){
                if(hash_t(needle) == hash_t(haystack.substr(i,n))){
                    return i;
            return -1;

Log in to reply

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