Clean brute-force implementation


  • 0
    N

    TIME: O(mn)
    SPACE: O(1)

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

Log in to reply
 

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