My accepted soluting using brute force method and goto statement


  • 0
    H
    class Solution {
    public:
        char *strStr(char *haystack, char *needle) {
            //brut-force method
            int n = strlen(haystack);
            int m = strlen(needle);
            int i,j,k;
            if(m == 0)
                return haystack;
            if(m == n)
                if(!strcmp(haystack,needle))
                    return haystack;
                else
                    return NULL;
      
            for(i=0;i<n-m;i++){
          out:        k = i;
                if(i == n-m)
                    return NULL;
                for(j=0;j<m;j++){
                    if(haystack[k] != needle[j]){
                           i++;
                          goto out;
                     }
                   else
                        k++;
                }
                if(j==m)
                return &haystack[i];
            }
            return NULL;
        }
    };`enter code here`

  • 0
    S

    class Solution {
    public:
    int strStr(char *haystack, char *needle)
    {
    int n = strlen(haystack);
    int m = strlen(needle);
    int i,j,k;

        for(i=0;i<=n-m;i++)
        {
            k = i;
            for(j=0;j<m;j++)
            {
                if(haystack[k] != needle[j])
                {
                      break;
                 }
               else
                k++;
            }
            if(j==m)
            return i;
        }
        return -1;
    }
    

    };


Log in to reply
 

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