题目

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.

代码

class Solution {
public:
int strStr(string haystack, string needle) {
const size_t len_hay = haystack.size();
const size_t len_nee = needle.size();
if ( len_hay < len_nee ) return -;
bool if_match = true;
for ( size_t i = ; i <= len_hay-len_nee; ++i )
{
if_match = true;
for ( size_t j = ; j < len_nee; ++j ){
if (haystack[i+j]!=needle[j]){
if_match = false;
break;
}
}
if ( if_match ){
return i;
}
}
return -;
}
};

Tips:

利用标志变量,暴力解决方法。时间复杂度O(m×n),空间复杂度O(1)

貌似还有个KMP算法,这个可以做到O(m+n)的时间复杂度,但是空间复杂度牺牲到了O(m)。明天再看KMP算法,这个效率的提升还是蛮高的,直接提高到了线性复杂度。

=========================================================================

这个blog讲解kmp算法挺详细的

http://blog.csdn.net/v_july_v/article/details/7041827

结合上面的blog,弄明白kmp算法,总结起来就是两点:

1. 弄明白next这个数组是怎么得来的。

2. 弄明白如何利用next数组不让haystack的指针回溯的

代码:

class Solution {
public:
int strStr(string haystack, string needle) {
int *next = new int[needle.length()];
Solution::getNext(needle,next);
size_t i = ;
size_t j = ;
while ( i<haystack.length() && j<needle.length() ){
if ( haystack[i]!=needle[j] ){
if ( next[j]==- ){
j=;
++i;
}
else{
j = next[j];
}
}
else{
++i;
++j;
}
}
return j==needle.length() ? i-j : -;
}
static void getNext(std::string needle, int next[])
{
int k = -;
next[] = k;
int len = needle.length();
int j = ;
while ( j<len- ){
if ( k==- || needle[j]==needle[k] ){
++k;
++j;
if ( needle[j]==needle[k] ){
next[j] = next[k];
}
else{
next[j] = k;
}
}
else{
k = next[k];
}
}
}
};

KMP这个算法非常精妙,总的来说就是不回溯haystack上的指针i,只移动needle上的指针j。

http://www.ituring.com.cn/article/59881

这片讲KMP的blog图画的好。

==================================================================

AC之后又回顾了整个过程,个人总结两个理解的关键点如下:

(1)

getNext中的k和j各代表什么含义?

k:不断迭代中,needle[j]之前所有元素中(不包括needle[j]),可能满足条件的最大匹配前后缀的长度(0~k-1)。这里的“条件”指的是needle[j]=needle[k]。

(2)

又想到一个问题,为什么当needle[j]!=needle[k]的时候,k=next[k]而不是--k?

原因在下面的日志中找到了(http://blog.csdn.net/thisinnocence/article/details/38544719

截取片段的红字部分是理解的关键,道理也是这个道理,但自己没有总结的这么精炼,所以直接截图引用了。

至此,KMP这个算法的序列就结束了。算法的一些细节算是吃透了,以后再巩固。

====================================================

第二次过这道题,直接放弃了KMP等算法,这个知道有就好了;只写了一个暴力解决的算法。

class Solution {
public:
int strStr(string haystack, string needle) {
if ( haystack.size()<needle.size() ) return -;
if ( needle.size()== ) return ;
for ( int i=; i<haystack.size()-needle.size()+; ++i )
{
if ( haystack[i]==needle[] )
{
bool find = true;
for ( int j=; j<needle.size(); ++j )
{
if ( haystack[i+j]!=needle[j] ) { find=!find; break; }
}
if ( find ) { return i; }
}
}
return -;
}
};

【Implement strStr() 】cpp的更多相关文章

  1. 【WildCard Matching】cpp

    题目: Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single charact ...

  2. 【LRU Cache】cpp

    题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...

  3. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  4. Hdu 4734 【数位DP】.cpp

    题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...

  5. 【 Sqrt(x) 】cpp

    题目: Implement int sqrt(int x). Compute and return the square root of x. 代码: class Solution { public: ...

  6. 【Single Number】cpp

    题目: Given an array of integers, every element appears twice except for one. Find that single one. No ...

  7. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  8. 【Next Permutation】cpp

    题目: Implement next permutation, which rearranges numbers into the lexicographically next greater per ...

  9. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

随机推荐

  1. Python网络编码

    #-*- coding:utf-8 -*- from SocketServer import ThreadingTCPServer, StreamRequestHandler import trace ...

  2. Java调第三方的webservice接口

    1.eclipse中add dynamic web project 2.选中项目右键new——> webservice ——> webservice client 在service def ...

  3. jquery的上传控件uploadly,每行都有一个这样的控件对id选择器的使用

    1.先看看预览图 这个是我的页面,其中如果我没点击添加一行的时候,会把本来有的数据进行循环出来,这个时候每个记录都必须有个上传图片的按钮,但是jquery的uploadly这个控件只是锁定id的,至少 ...

  4. IOS基础——IOS学习路线图(一)

    一.一个月 1.OC语法基础. 2.KVC和KVO 3.IOS UI基础 4.UI表视图与集合视图 5.UIStoryboard和autoLayout 6.Ipad API 二.10天 7.静态页面考 ...

  5. Dynamic Prompt Table for Record Field on PeopleSoft Page

    Sometimes a situation in project work arises to have a dynamic prompt table for record fields on Peo ...

  6. C#实现图书馆程序导入ISO-2709格式(MARC)功能

    1.导入 /// <summary> /// 导入ISO2709 /// </summary> /// <param name="sender"> ...

  7. ThinkPHP之中的事务回滚

    小李子 获取thinkphp之中执行的SQL: 1.用调试模式的追踪trace功能: 2.代码: $user_type=D('user_type'); $datass=array('school_id ...

  8. js浏览器各种位置检测

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. mysql查询语句(mysql学习笔记七)

    Sql语句 一般顺序GHOL : group by,having ,order by,limit     如果是分组,应该使用对分组字段进行排序的group by语法                 ...

  10. js 月历 时间函数 月份第一天 星期的判断

    返回值为0-6,其中返回值0为星期天:如同,php中的日期函数一样判断.