zoukankan      html  css  js  c++  java
  • 实现strStr()函数

    方法一:暴力解法

     1 int strStr(string haystack, string needle) {
     2     if (needle.empty())
     3         return 0;
     4 
     5     int M = haystack.size();
     6     int N = needle.size();
     7 
     8     for (int i = 0; i <= M - N; i++)
     9     {
    10         int j;
    11         for (j = 0; j < N; j++)
    12         {
    13             if (needle[j] != haystack[i + j])
    14             {
    15                 break;
    16             }
    17         }
    18         if (j == N)
    19             return i;
    20     }
    21     return -1;
    22 }

    方法二:利用memcmp,一层for循环即可解决

     1 int strStr(string haystack, string needle) {
     2     if (needle.empty())
     3         return 0;
     4 
     5     int M = haystack.size();
     6     int N = needle.size();
     7 
     8     char* m = new char[M + 1];
     9     char* n = new char[N + 1];
    10 
    11     memcpy(m, haystack.c_str(), M);
    12     memcpy(n, needle.c_str(),    N);
    13     m[M] = '';
    14     n[N] = '';
    15 
    16     for (int i = 0; i <= M - N; i++)
    17     {
    18         if (0 == memcmp(&m[i], n, N))
    19         {
    20             delete[] m;
    21             delete[] n;
    22             return i;
    23         }
    24     }
    25 
    26     delete[] m;
    27     delete[] n;
    28 
    29     return -1;
    30 }

    方法三: KMP算法

  • 相关阅读:
    Django-xadmin
    Django-DRF框架中认证与权限
    Django-DRF视图集
    Django-DRF序列化器
    javascript
    web-api
    ES6语法
    Redis缓存雪崩、击穿、穿透
    Jetbrains IDEA 系列软件最新crack方案
    jmeter设置代理服务器录制脚本
  • 原文地址:https://www.cnblogs.com/ll-10/p/11650348.html
Copyright © 2011-2022 走看看