My 4ms C++ solution, brute force, but easy to understand


  • -1
    J
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int pHay = 0;
            int pNee = 0;
            int lHay = haystack.length();
            int lNee = needle.length();
            
            if (lNee == 0)
                return 0;
            
            
            while(pHay != lHay)
            {
                if (haystack[pHay] == needle[pNee])
                {
                    if (pNee == lNee-1)
                    {
                        break;
                    }
                    else
                    {
                        ++pNee;
                        ++pHay;
                    }
                }
                else // (haystack[pHay] != needle[pNee])
                {
                    if (pNee != 0)
                    {
                        pHay = pHay - pNee + 1;
                        pNee = 0;
                        continue;
                    }
                    else
                    {
                        ++pHay;
                    }
                }
            }
            
            if (pHay == lHay)
                return -1;
            else
                return pHay - lNee + 1;
        } 
    };

  • 0
    C

    someone tell me why my code costs so much time!!!

    class Solution {
    public:
    int strStr(string haystack, string needle) {

        if (needle.length() <= 0) return 0;
        if (needle.length() > haystack.length()) return -1;
        int i = 0, j = 0, len_h = haystack.length(), len_n = needle.length();
        while (i < len_h) {
            j = 0;
            while (j < len_n && needle[j] == haystack[i]) {j++, i++;};
            if (j == len_n) return i - j;
            i = i - j + 1;
        }
        return -1;
    }
    

    };


  • 0
    C

    well, i see.


Log in to reply
 

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