zoukankan      html  css  js  c++  java
  • LeetCode(28)题解:Implement strStr()

    https://leetcode.com/problems/implement-strstr/

    题目:

    Implement strStr().

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

    思路:

    判断一个string是否另一个string的子序列并返回位置。

    naive法:遍历查找,复杂度O(mn)。

    advance法还有Rabin-Karp, KMP, Boyer- Moore algorithm等。

    AC代码:

     1 class Solution {
     2 public:
     3     int strStr(string haystack, string needle) {
     4         int m=haystack.size();
     5         int n=needle.size();
     6         if(n==0 && m==0)
     7             return 0;
     8         bool flag=true;
     9         for(int i=0;i<m-n+1;i++){
    10             for(int j=0;j<n;j++){
    11                 if(needle[j]!=haystack[i+j]){
    12                     flag=false;
    13                     break;
    14                 }
    15             }
    16             if(flag==true){
    17                 return i;
    18             }
    19             else
    20                 flag=true;
    21         }
    22         return -1;
    23     }
    24 };
  • 相关阅读:
    CF359B Permutation
    CF859C Pie Rules
    Contest 156
    Contest 155
    Range Module
    python-环境
    Git 使用
    Contest 154
    生命是一种长期而持续的累积过程
    Contest 153
  • 原文地址:https://www.cnblogs.com/aezero/p/4645181.html
Copyright © 2011-2022 走看看