28. Implement strStr()

mplement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

S1: brutal force

    int strStr(string haystack, string needle) {
        int size_h = haystack.size(), size_n = needle.size();
        for(int i = 0; i <= size_h-size_n; ++i){
            int j = 0;
            while(i+j < size_h && j < size_n && haystack[i+j] == needle[j]){
                j++;
            }
            if(j == size_n) return i;
        } 
        return -1;
    }

S2: KMP

459. Repeated Substring Pattern

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1: Input: "abab"

Output: True

Explanation: It's the substring "ab" twice. Example 2: Input: "aba"

Output: False Example 3: Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) Show Company Tags Show Tags Show Similar Problems

S: numeration

枚举所有可能的substring

    bool repeatedSubstringPattern(string str) {
        int size = str.size();
        for(int slot = 1; slot <= size/2; ++slot){
            if(size%slot != 0) continue;
            int idx = slot, j = 0;
            while(idx+j < size && str[idx+j] == str[j%slot]) j++;
            if(idx+j == size) return true;
        }
        return false;
    }

results matching ""

    No results matching ""