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;
    }


     
  • 相关阅读:
    net下开发COM+组件(一)
    C#中自定义属性的例子
    textBox的readonly=true
    关于ADO.Net的数据库连接池
    CYQ.Data 轻量数据层之路 使用篇三曲 MAction 取值赋值(十四)
    CYQ.Data 轻量数据层之路 SQLHelper 回头太难(八)
    CYQ.Data 轻量数据层之路 MDataTable 绑定性能优化之章(十一)
    C# 浅拷贝与深拷贝区别 解惑篇
    C#中的 ref 传进出的到底是什么 解惑篇
    CYQ.Data 轻量数据层之路 使用篇五曲 MProc 存储过程与SQL(十六)
  • 原文地址:https://www.cnblogs.com/ganeveryday/p/4933935.html
Copyright © 2011-2022 走看看