Simple c++ solution


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

  • 0
    C

    Nice solution!


Log in to reply
 

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