4ms using c++, didn't use kmp,easy to understand


  • 2
    Q
    class Solution {
    public:
    int strStr(string h, string n) {
        int j;
        if(n.size()==0)
            return 0;
        for(int i=0;i<=(int)(h.length()-n.length());i++)
        {
            for(j=0;j<n.length();j++)
            {
                if(h[i+j]!=n[j])
                   break;
            }
            if(j==n.length())
               return i;
        }
        return -1;
       }
     };
    

    I am a Chinese ,and I want to make friends with you, then we can talk about problems. And I want to improve my English.

    My email : skyqsk@126.com


  • 0
    F

    This is commonly used method.In fact, it is very inefficient.And why it's 4ms,because the system uses the test string is relatively short.If the use of long strings of words........


  • 0

    No fnatic, there is a condition h.length()-n.length()
    So, actually it runs O(mn - nn) if m and n both too long it runs O(n).
    In other case, if m is very larger than n, it is almost O(m).

    The worst case is n = m/2 which it runs far more time than KMP


Log in to reply
 

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