码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode] implement strStr() (C++)

时间:2014-11-09 06:16:02      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   div   on   

题目:

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.

Tag:

String; Two Pointers

体会:

这道题是字符串的匹配问题,目前还只会朴素的逐步方法,但是这道题还有KMP解法,和Boyer-Moore的解法,目前还没有掌握。

先把笔记放到这里,以后再来解决吧。

1. KMP算法

2. Boyer-Moore算法

 1 class Solution {
 2 public:
 3     int strStr(char *haystack, char *needle) {
 4         int i = 0;
 5         int j = 0;
 6         while (haystack[i] && needle[j] ) {
 7             if (haystack[i] == needle[j]) {
 8                 i++;
 9                 j++;
10             } else {
11                 i = i - j + 1;
12                 j = 0;
13             }
14         }
15         return (needle[j] ? -1 : i - j);
16     }
17 };

 

 

[Leetcode] implement strStr() (C++)

标签:style   blog   http   io   color   ar   sp   div   on   

原文地址:http://www.cnblogs.com/stevencooks/p/4084357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!