LC 28. Implement strStr()

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    int strStr(string haystack, string needle) {
        char* p;
        int n1 = haystack.size(),n2 = needle.size();
        char s1[n1+1],s2[n2+1];
        for(int i=0;i<n1;i++){
            s1[i] = haystack[i];
        }
        s1[n1] = '\0';
        for(int i=0;i<n2;i++){
            s2[i] = needle[i];
        }
        s2[n2] = '\0';
        p = strstr(s1, s2);
        if(p==NULL){
            return -1;
        }
        int newLen = strlen(p);
        return n1-newLen;
    }
};


Dicussion Forum