zoukankan      html  css  js  c++  java
  • [LeetCode] Implement strStr()

    Implement strStr().

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

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2
    

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1

    使用KMP算法来overwrite strStr()

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            if(needle.empty()) return 0;
            if(haystack.empty()) return -1;
            return kmp(haystack, needle);
        }
        
        int kmp(string haystack, string needle)
        {
            vector<int> next = getNext(needle); 
            int sLen = haystack.size(), tLen = needle.size();
            int i = 0, j = 0, res = -1;
            while (i < sLen)
            {
                if (j == -1 || haystack[i] == needle[j])
                {
                    ++i;
                    ++j;
                }
                else
                {
                    j = next[j];
                }
                if (j == tLen)
                {
                    res = i - tLen;
                    break;
                }
            }
            return res;
        }
        
        vector<int> getNext(string needle)
        {
            vector<int> next(needle.size(), -1);
            int tLen = needle.size();
            int i = 0, j = -1;
            while (i < tLen - 1)
            {
                if (j == -1 || needle[i] == needle[j])
                {
                    ++i;
                    ++j;
                    next[i] = j;
                }
                else
                {
                    j = next[j];
                }
            }
            return next;
        }
    };
    // 7 ms
  • 相关阅读:
    二分查找
    泛型 学习
    一个时间转换的功能的类
    TCP/IP、Http、Socket的区别
    值得学习的
    popupwindow使背景变暗
    设计模式最好的学习网站
    观察者模式
    数据报的使用
    网络编程server
  • 原文地址:https://www.cnblogs.com/immjc/p/8543882.html
Copyright © 2011-2022 走看看