Why is my time limit exceeding on this code? Could you just explain to me how to improve my code?


  • 0
    A
     class Solution {
     public:
     int strStr(string haystack, string needle) {
     int needleLen = needle.length();
        
        string control = "";
        bool match = true;
        
        if((haystack.length() == 0) && (needleLen == 0)) {
            return 0;
        }
        
        if(haystack.length() < needle.length()) {
            return -1;
        }
        
        for(int i = 0; i < haystack.length(); i++) {
            match = true;
            for(int j = 0; j < needleLen; j++) {
                if(needle[j] != haystack[i + j]) {
                    match = false;
                    break;
                }
            }
            if(match == true) {
                return i;
            }
        }
        
        return -1;
    }
    };

Log in to reply
 

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