Brute force solution


  • 0
    C
    class Solution {
    public:
        int strStr(string haystack, string needle) 
        {
            if( !needle.size() ) return 0;
            
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            int difference = (int)haystack.size() - (int)needle.size();
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            for(int i=0; i <= difference; i++)
            {
                int k=0;
                for(int j=i; k < needle.size(); j++, k++)
                    if(haystack[j] != needle[k]) break;
                    
                if(k >= needle.size()) return i;
            }
            
            return -1;
        }
    };

Log in to reply
 

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