zoukankan      html  css  js  c++  java
  • 2021.1.27 刷题(KMP字符串匹配)

    题目链接:https://leetcode-cn.com/problems/implement-strstr
    题目描述:
    实现 strStr() 函数。
    给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

    示例 1:
    输入: haystack = "hello", needle = "ll"
    输出: 2

    示例 2:
    输入: haystack = "aaaaa", needle = "bba"
    输出: -1

    解题:

    class Solution {
    public:
        
        //求最长公共前后缀表
        vector<int> prefix_table(string pattern, int n)
        {
            vector<int> prefix(n, 0);
            int j = 0; //前缀指针
             for(int i = 1; i < n; i++)  //后缀指针
             {
                while (j - 1 >= 0 && pattern[j] != pattern[i]){
                    j = prefix[j - 1];//最前缀指针跳动
                }
                if(pattern[j] == pattern[i]){
                    j++;
                    prefix[i] = j;
                }
            }
            return prefix;
        }
    
    
        // //prefix表右移一位,得next表
        // void next(vector<int> prefix, int n) 
        // {
        //     for(int i = n - 1; i > 0; i--)
        //     {
        //         prefix[i] = prefix[i - 1];
        //     }
        //     prefix[0] = -1;
        // }
    
        int strStr(string haystack, string needle) {
            int haystack_len = haystack.size();
            int needle_len = needle.size();
            vector<int> next;
            //特判
            if(needle_len == 0)
                return 0;
            if(haystack_len < needle_len)
                return -1;
            next = prefix_table(needle, needle_len);
            int i = 0; //i指向主串的指针
            int j = 0; //j指向模式串的指针
    
            for(i; i < haystack_len; i++)
            {
                while(j - 1 >= 0 && haystack[i] != needle[j])
                {
                    j = next[j - 1]; //回退
                }
                if(haystack[i] == needle[j])
                {
                    j++;
                    if(j == needle_len)
                    {
                        return i - needle_len + 1;
                    }
                }
            }
    
            return -1;
    
        }
    };
    
  • 相关阅读:
    redis中save和bgsave区别
    scrapy生成json中文为ASCII码解决
    mysql数据库,创建只读用户
    memcached命令行、Memcached数据导出和导入
    Memcache 查看列出所有key方法
    Elasticsearch5.x 引擎健康情况
    docker容器创建MariaDB镜像
    大文本数据排序
    换行符 和回车符
    索引与文本文件
  • 原文地址:https://www.cnblogs.com/ZigHello/p/14336335.html
Copyright © 2011-2022 走看看