zoukankan      html  css  js  c++  java
  • LeetCode 28

    一、问题描述

    Description:

    Implement strStr().

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

    实现函数strStr(string haystack, string needle),用于字符串匹配。

    • 若字符串匹配成功,返回 needle 在 haystack 中第一次出现的位置。
    • 若字符串匹配不成功,返回-1。


    二、解题报告

    解法一:朴素的字符串匹配

    朴素的字符串匹配算法就是:枚举 0snm 的所有起点,检查是否满足条件P[1...m] = T[s+1...s+m]

    代码很简洁:

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

    AC 时间 4ms 。


    解法二:KMP算法

    class Solution {
    public:
        int* prefixFunction(string pattern)
        {
            int len = pattern.size();
            int k = 0;
    
            int *pi = new int[len];
            for(int i=0; i<len; i++)     // 初始化为0
                pi[i] = 0;
    
            for(int i=1; i<len; i++)
            {
                while (k>0 && pattern[k]!=pattern[i])
                    k = pi[k-1];
    
                if (pattern[k]==pattern[i])
                    k = k+1;
    
                pi[i] = k;
            }
    
            return pi;
        }
    
        int strStr(string haystack, string needle)
        {
            if(needle == "")
                return 0;
    
            int n = haystack.size();
            int m = needle.size();
            int *pi = prefixFunction(needle);
    
            int q=0;
            for(int i=0; i<n; i++)
            {
                while (q>0 && needle[q]!=haystack[i])
                    q = pi[q-1];
    
                if (needle[q]==haystack[i])
                    q = q+1;
    
                if ( q == m )
                    return i - m + 1;
            }
            return -1;
        }
    };

    AC 时间 4ms 。





    LeetCode答案源代码:https://github.com/SongLee24/LeetCode


  • 相关阅读:
    .NET 几种数据绑定控件的区别
    .NET 使用 Highcharts生成扇形图 柱形图
    使用Jquery1.9 版本 来实现全选
    30款jQuery常用网页焦点图banner图片切换
    MVC中使用MVCPager简单分页
    HttpWebRequest 以及WebRequest的使用
    C#中的事件机制
    如何向妻子解释OOD (转)
    linux 设置时间
    git 使用操作
  • 原文地址:https://www.cnblogs.com/songlee/p/5738038.html
Copyright © 2011-2022 走看看