Leetcode 28:实现strStr()

@[TOC](Leetcode 28:实现strStr())

题目描述

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1:

输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:

输入: haystack = “aaaaa”, needle = “bba”
输出: -1
说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

我的解法(暴力超时)

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

暴力不超时解法

加了一个两字符串长度比较的判断,运行时间超过百分之七十多解答,还可以。

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

KMP算法

详细说明见 https://blog.csdn.net/starstar1992/article/details/54913261

class Solution {
public:
    vector<int> get_next(string needle){
        vector<int> next;
        next.push_back(-1);//next[0]初始化为-1,-1表示不存在相同的最大前缀和最大后缀
        int k = -1;//k初始化为-1
        for(int q = 1; q < needle.size(); q ++){
            while(k > -1 && needle[k+1] != needle[q]){//如果下一个不同,那么k就变成next[k],注意next[k]是小于k的,无论k取任何值。
                k = next[k];//往前回溯
            }
            if(needle[k+1] == needle[q]){
                k ++;
            }//如果相同,k++
            next.push_back(k);//这个是把算的k的值(就是相同的最大前缀和最大后缀长)赋给next[q]
        }
        return next;
    }
    
    int strStr(string haystack, string needle) {
        if(needle.empty()){return 0;}
        int k = -1;
        vector<int> next = get_next(needle);//计算next数组
        for(int i = 0; i < haystack.size(); i ++){
            while(k > -1 && needle[k + 1] != haystack[i]){
                k = next[k];
            }//ptr和str不匹配,且k>-1(表示ptr和str有部分匹配)
            if(needle[k+1] == haystack[i]){
                k ++;
            }
            if(k == needle.size() - 1){return i - k;}
        }//说明k移动到ptr的最末端
        return -1;//说明未匹配
    }
};

库函数

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty())
            return 0;
        int pos=haystack.find(needle);
        return pos;
    }
};

其它算法

BM算法
Sunday

发布了23 篇原创文章 · 获赞 9 · 访问量 1439

猜你喜欢

转载自blog.csdn.net/IcdKnight/article/details/96298215