题目

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. 字符串匹配KMP算法

    1. 字符串匹配的KMP算法 2. KMP算法详解 3. 从头到尾彻底理解KMP

  2. java编程思想第四版中 net.mindview.util包

    操作系统: win8.1 编译环境 JDK1.6 编辑器 notepad++ 第48页练习8 1 下载相应程序包 Thinking in Java 4ed - CODE 2 设置相应的CLASSPAT ...

  3. sql server2005 实现读写分离

    下面我们重点介绍Sql Server 2005是如何实现负载均衡的. Sql Server 2005的新特性 端到端拓扑的事务性复制 SQL Server 2005对端到端(P2P)拓扑结构上事务性的 ...

  4. c#生成随机数示例分享

    c#生成(随机数 http://www.jbxue.com/tags/suijishu.html)的代码. /// 构造随机数 种子 ];             System.Security.Cr ...

  5. 生日蛋糕 (codevs 1710) 题解

    [问题描述] 7月17日是Mr.W的生日,ACM-THU为此要制作一个体积为Nπ的M层生日蛋糕,每层都是一个圆柱体. 设从下往上数第i(1<=i<=M)层蛋糕是半径为Ri,高度为Hi的圆柱 ...

  6. Castle 集锦

    Castle Windsor http://www.cnblogs.com/RicCC/archive/2010/03/30/castle-windsor-ioc-di.html 官方配置说明(反正我 ...

  7. 3.第一个python程序

    学习任何一门语言的第一步,首先要写个'hello world',这算是程序员的一个传统.但在写之前,还有注意几个问题. 首先,python是一门脚本语言,而脚本语言的特点就是:我们写的代码会先由解释器 ...

  8. 插值和空间分析(二)_变异函数分析(R语言)

    方法1.散点图 hscat(log(zinc)~, meuse, (:)*) 方法2.变异函数云图 library(gstat) cld <- variogram(log(zinc) ~ , m ...

  9. oracle11g 重新配置em

    OS: ORACLE-LINUX 5.7 DB: 11.2.0.3 [oracle@b28-122 ~]$ emctl status dbconsoleOracle Enterprise Manage ...

  10. sql server 2016 management studio没有的解决方式

    最近安装sql sever2016后发现没有 management studio管理工具,无法操作sql server,可以单独下载安装后即可. 下载地址: https://msdn.microsof ...