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

    Description:

    Implement strStr().

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

    Code1:

    vector<int> getNext ( string&t  )
    {
        size_t n = t.length();
        vector<int>next(n,-1);
    
        int i = 0, j = -1;
        while ( i < n-1 )
        {
            if ( j == -1 || t[i] == t[j])
            {
                ++i;
                ++j;
                next[i] = j;
            }
            else
                j = next[j];
        }return next;
    }
    int indexKMP( string& t, string&w, vector<int>& next )
    {
        int i = 0, j = 0;
        int lengthT = t.length();
        int lengthW = w.length();
    
        while ( i < lengthT && j < lengthW )
        {
            if ( j == -1 || t[i] == w[j] )         //继续比较后继字符
            {
                ++i;
                ++j;
            }
            else
                j = next[j];
        }
        if ( j == lengthW )
            return i - lengthW;
        else
            return -1;
    }
        int strStr(string haystack, string needle) {
            if (needle == "")
                return 0;
            if (haystack == "")
                return -1;
         vector<int>next;
         next = getNext(needle);
          return indexKMP(haystack,needle,next);
           return -1;
        }

     Code2:

    int strStr(string a, string b)
    {//a为目标串,b为字串
          if (b == "")
                return 0;
            if (b.size() > a.size() )
                return -1;
        for (int i = 0; i <= a.size()-b.size(); ++i)
        {
            int j = 0;
            for (; j < b.size(); ++j)
            {
                if (a[i+j]!=b[j])
                    break;
            }
            if (j==b.size())
                return i;
        }
        return -1;
    }
  • 相关阅读:
    11.tp5常见漏洞
    10.tp3常见漏洞
    1.linux分析排查
    3.docker镜像探究
    1.docker概述
    4.docker常用命令
    2.docker安装
    3.windows分析排查
    9.thinkphp框架模型
    2.win2k8搭建asp网站
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4774034.html
Copyright © 2011-2022 走看看