您的位置:首页 > 其它

[Leetcode] Implement strStr()

2014-10-02 04:46 253 查看
题目:

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思路一:Brute Force

        从源串的每一个字符开始匹配目标串,发现不匹配目标串回溯到第一个字符,重新匹配源串的下一个字符。循环终点是匹配完源串的最后一个字符,但事实上,当发现源串指针指向'\0'且目标串指针并未指向'\0'时,源串剩余的长度以不足以匹配目标串,应返回空指针。

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        int start_addr = (int)haystack;
        char* src = haystack;
        char* dst = needle;
        while (*haystack != '\0') {
            if (*dst == '\0') {   //whole string matched
                return (int)haystack - start_addr;
            } else if (*src == '\0') {   //the source string is not long enough
                return -1;
            } else if (*src == *dst) {   //character matched
                src++;
                dst++;
            } else {   //character not matched, backtracking
                src = ++haystack;
                dst = needle;
            }
        }
        if (*dst == '\0') return (int)haystack - start_addr;
        else return -1;
    }
};


思路二:KMP算法

       在很多情况下,通常没有必要回溯到最初位置重新匹配。KMP的整体思想是利用next数组记录回溯的位置。

        KMP算法的核心思想是,对于目标串S[0, 1, 2, ... , n],当发现不匹配时,目标串仅需要向前回溯到位置P即可。对于目标串中的每一个字符,P的值不同。因此需要一个数组来记录每一个字符需要回溯到的位置P。

        P的计算如下。对于字符串
S[0, 1, 2, ... , n], 任意子串S'[0, 1, 2, ..., m] (m < n)为该串的前缀,子串S'[m, m + 1, m + 2, ..., n] (m > 0)为该串的后缀。设当前不匹配的字符为S
,那么P为字符串S’[0, 1, 2, ...
, n - 1]中能够匹配的后缀的前缀中最长的那个前缀的下一个字符。例如,目标串为abcdabcf,当在字符f处发现不匹配时,目标串需回溯到d,因为对于字符串abcdabc,能够匹配后缀的最长前缀为abc,下一个位置即为d。比较直观的解释是,abcdabcf既然匹配到字符f,那么源串中必然匹配了f的前面3个字符abc;既然后缀可以匹配abc,那匹配后缀的前缀必然也可以匹配abc,因此回溯到d字符继续匹配。

 
      因此,当得到记录每一个字符回溯位置的next数组后,利用两个指针对源串和目标串进行匹配,发现不匹配时目标串指针回溯到指定位置,继续匹配。循环进行到发现匹配串(即目标串指针移动到末尾)或源串匹配结束(即源串指针移动到末尾)。

 
      对于next数组的计算,不提供证明,下面是比较直观的叙述。

 
      利用两个指针i和j,i为当前需计算的字符,j为当前能匹配的最长前缀的位置。假设S[i] == S[j],那么S[0, 1, ... , j]即为S[0, 1, ... , i + 1]的最长前缀,那么当S[i+1]不匹配时,需要回溯到j + 1。这就是代码中if (j == -1 || needle[i] == needle[j])
里面的部分。j = -1的情况,可以解释为当前没有可以匹配后缀的前缀,那么需要回溯到目标串的开始位置,即next[i] = 0. 当S[i] != S[j]时,将j回溯到上一个最长前缀处继续判断,最多回溯到j = -1处。

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        int len_haystack = (int)strlen(haystack);
        int len_needle = (int)strlen(needle);
        int i = 0;
        int j = -1;   //the length of prefix that matches the postfix
        vector<int> next(len_needle);
        if (len_needle > 0) {
            next[0] = -1;
            while (i < len_needle - 1) {
                if (j == -1 || needle[i] == needle[j]) {   //increase the prefix by 1
                    i++;
                    j++;
                    next[i] = j;   //record
                } else {
                    j = next[j];   //backtrack to the previous smaller prefix to see if they match
                }
            }
        }
        i = 0;
        j = 0;
        while (i < len_haystack && j < len_needle) {
            if (j == -1 || haystack[i] == needle[j]) {
                i++;
                j++;
            } else {   //backtracking
                j = next[j];
            }
        }
        if (j == len_needle) return i - j;
        else return -1;
    }
};

总结:KMP算法牺牲空间换取时间。Brute Force复杂度为O(mn), KMP算法复杂度为O(m + n).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: