zoukankan      html  css  js  c++  java
  • 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;
    }


     
  • 相关阅读:
    ACdream 1224 Robbers (贪心)
    HDU 4320 Arcane Numbers 1 (质因子分解)
    在脚本中重定向输入
    呈现数据
    shell中的for、while、until(二)
    shell中的for、while、until
    C 指针疑虑
    结构化命令
    fdisk -c 0 350 1000 300命令
    PC机上的COM1口和COM2口
  • 原文地址:https://www.cnblogs.com/ganeveryday/p/4933935.html
Copyright © 2011-2022 走看看