Simple c++ 6ms solution


  • 0
    A
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            if (needle == "") return 0;
            if (haystack == "") return -1;
            if (needle.size() > haystack.size()) return -1;
            for (int i=0; i<haystack.size(); i++) {
                if (haystack[i] != needle[0]) continue;
                if (haystack.size()-i < needle.size()) return -1;
                bool isIn = true;
                for (int j=0; j<needle.size(); j++) {
                    if (haystack[i+j] != needle[j]) {
                        isIn = false;
                        break;
                    }
                }
                if (isIn == 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.