zoukankan      html  css  js  c++  java
  • 【LeetCode】28. Implement strStr() (2 solutions)

    Implement strStr()

    Implement strStr().

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

    解法一:暴力解

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

    解法二:标准KMP算法。可参考下文。

    KMP算法详解

    (1)先对模式串needle做“自匹配”,即求出模式串前缀与后缀中重复部分,将重复信息保存在next数组中。

    (2)依据next数组信息,进行haystack与needle的匹配。

    class Solution {
    public:
        int strStr(char *haystack, char *needle) {
            int hlen = strlen(haystack);
            int nlen = strlen(needle);
            int* next = new int[nlen];
            getNext(needle, next);
            int i = 0;
            int j = 0;
            while(i < hlen && j < nlen)
            {
                if(j == -1 || haystack[i] == needle[j])
                {// match current position, go next
                    i ++;
                    j ++;
                }
                else
                {// jump to the previous position to try matching
                    j = next[j];
                }
            }
            if(j == nlen)
            // all match
                return i-nlen;
            else
                return -1;
        }
        void getNext(char *needle, int next[])
        {// self match to contruct next array
            int nlen = strlen(needle);
            int j = -1;     // slow pointer
            int i = 0;      // fast pointer
            next[i] = -1;    //init next has one element
            while(i < nlen-1)
            {
                if(j == -1 || needle[i] == needle[j])
                {
                    j ++;
                    i ++;           //thus the condition (i < nlen-1)
                    next[i] = j;    //if position i not match, jump to position j
                }
                else
                {
                    j = next[j];    //jump to the previous position to try matching
                }
            }
        }
    };

  • 相关阅读:
    2653 区间xor
    c++位运算
    洛谷P1233 木棍加工
    c++背包问题
    FOC基本调试方法[转]
    用于下载AD官网登录账号:User name: fuxin918@fuxin918.com Passeword: s6c0W1w8
    STC10F10XE定时器中断输出10KHz的方波程序
    学习DSP(三)安装C2833x/C2823x C/C++ 头文件和外设示例-压缩包
    学DSP(二):目标芯片28335,GO!
    学DSP(一):开始
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3753981.html
Copyright © 2011-2022 走看看