Self-explanatory elegant C++ solution, beats > 90% (3 ms)


  • 0
    C
    class Solution {
        bool startsWith(const string& haystack, const string& needle, int start)
        {
            int needlestart = 0;
            while(start < haystack.size() and needlestart < needle.size())
            {
                if(haystack[start] != needle[needlestart])
                    return false;
                start++;
                needlestart++;
            }
            return true;
        }
        
    public:
        int strStr(string haystack, string needle) {
            if(needle.empty())
                return 0;
            
            int i = 0;
            int h_size = haystack.size(), n_size = needle.size();
            while(i <= h_size - n_size)
            {
                if(haystack[i] == needle[0] and startsWith(haystack, needle, i))
                    return i;
                i++;
            }
            return -1;
        }
    };
    

Log in to reply
 

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