博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Implement strStr()
阅读量:5980 次
发布时间:2019-06-20

本文共 2254 字,大约阅读时间需要 7 分钟。

Well, the problem does not aim for an advanced algorithm like KMP but only a clean brute-force algorithm. So we can traverse all the possible starting points of haystack (from 0 tohaystack.length() - needle.length()) and see if the following characters in haystack match those of needle.

The code is as follows.

1 class Solution { 2 public:  3     int strStr(string haystack, string needle) { 4         int m = haystack.length(), n = needle.length(); 5         if (!n) return 0; 6         for (int i = 0; i < m - n + 1; i++) { 7             int j = 0; 8             for (; j < n; j++) 9                 if (haystack[i + j] != needle[j])10                     break;11             if (j == n) return i;12         }13         return -1;14     }15 };

Of course, you may challenge yourself implementing the KMP algorithm for this problem.

KMP is a classic and yet notoriously hard-to-understand algorithm. However, I think the following two links give nice explanations. You may refer to them.

  1. ;
  2. , with a well-commented C code.

I am sorry that I am still unable to give a personal explanation of the algorithm. I only read it from the two links above and mimic the code in the second link.

My accepted C++ code using KMP is as follows. Well, it also takes 4ms -_-

1 class Solution { 2 public: 3     int strStr(string haystack, string needle) { 4         int m = haystack.length(), n = needle.length(); 5         if (!n) return 0; 6         vector
lps = kmpProcess(needle); 7 for (int i = 0, j = 0; i < m; ) { 8 if (haystack[i] == needle[j]) { 9 i++;10 j++;11 }12 if (j == n) return i - j;13 if (i < m && haystack[i] != needle[j]) {14 if (j) j = lps[j - 1];15 else i++;16 }17 }18 return -1;19 }20 private:21 vector
kmpProcess(string& needle) {22 int n = needle.length();23 vector
lps(n, 0);24 for (int i = 1, len = 0; i < n; ) {25 if (needle[i] == needle[len])26 lps[i++] = ++len;27 else if (len) len = lps[len - 1];28 else lps[i++] = 0;29 }30 return lps;31 }32 };

 

转载地址:http://vtlox.baihongyu.com/

你可能感兴趣的文章
关于List<T>集合中的差集
查看>>
Vue-router路由判断页面未登录跳转到登录页面
查看>>
Sql异常①
查看>>
leetcode-205-Isomorphic Strings
查看>>
Ubuntu下Apache2+Tomact7安装、配置及整合
查看>>
c++重载与覆写
查看>>
使用 JavaScript 将网站后台的数据变化实时更新到前端-【知乎总结】
查看>>
Java基础之j简析avax.swing.JOptionPane(一)showMessageDialog
查看>>
信息资源管理的标准与法规
查看>>
二进制、十进制、N进制 ○| ̄|_
查看>>
MD5加密 C#窗体应用程序
查看>>
Android 数据库管理— — —创建数据库
查看>>
Jquery 校验文本框只能输入负数、小数、整数
查看>>
关于固态硬盘SSD的4K对齐
查看>>
fanc委托在项目中使用
查看>>
C# FileStream 按大小分段读取文本内容
查看>>
WGS84,GCJ02, BD09坐标转换
查看>>
如何给网页标题栏上添加图标(favicon.ico)(转)
查看>>
[转载] Linux架构
查看>>
mysql授权
查看>>