• leetcode_28_ Implement strStr() (easy)


    Imple

    ment strStr()

    Implement strStr().

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

    Update (2014-11-02):
    The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.

    解题:

    要考虑“”,""情况,输出为0

    最初的写法,暴力法:
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            if(needle.length() == 0) {
                if(haystack.length() == 0)return 0;
                return -1;
            }
            for(int i =0;i<=haystack.length()-needle.length();i++){
                if(haystack.at(i)==needle.at(0)){
                    int y = i;
                    int equation = 0;
                    for(int j = 0;j<needle.length();j++,y++){
                        if(haystack.at(y)!=needle.at(j)){
                            equation = 1;
                            break;
                        }
                    }
                    if(!equation){
                        return i;
                    }
                }
            }
            return -1;
        }
         
    };
    超时
    然后:

    这道题的直接思路就是暴力查找,就是一个字符一个字符地进行匹配。不多说了,如果有兴趣,可以去研究这几个O(m+n)的算法:Rabin-Karp算法、KMP算法和Boyer-Moore算法。

    时间复杂度:O(mn)

    空间复杂度:O(1)

    #include <iostream>

    using namespace std;
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            if(haystack.length()<needle.length())return -1;//没有此句,会超时
            unsigned long al = haystack.length();
            unsigned long bl = needle.length();
            for(int i =0,j;i<=al-bl;i++){
                for( j = 0;j<needle.length()&&haystack.at(i+j)==needle.at(j);j++);
                    if(j==bl){
                        return i;
                    }
            }
            return -1;
        }
        
    };
    int main(int argc, const char * argv[]) {
        Solution c;
        string a;
        string b;
        while (1) {
            cout<<"start"<<endl;
            cin>>a;
            cin>>b;
            cout<<c.strStr(a, b)<<endl;
        }
     
        return 0;
    }


     
  • 相关阅读:
    第八届极客大挑战 Web-php绕过
    第八届极客大挑战 Web-故道白云&Clound的错误
    IMDB-TOP_250-爬虫
    任意角度图片旋转
    图片处理代码
    C#获取获取北京时间多种方法
    STL vector用法介绍
    C++ 用libcurl库进行http通讯网络编程
    CString 使用方法
    A星算法(游戏寻路算法)的C++实现(转)
  • 原文地址:https://www.cnblogs.com/ganeveryday/p/4933935.html
Copyright © 2020-2023  润新知