【Implement strStr() 】cpp
题目:
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的更多相关文章
- 【WildCard Matching】cpp
题目: Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single charact ...
- 【LRU Cache】cpp
题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...
- hdu 4739【位运算】.cpp
题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...
- 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~ ...
- 【 Sqrt(x) 】cpp
题目: Implement int sqrt(int x). Compute and return the square root of x. 代码: class Solution { public: ...
- 【Single Number】cpp
题目: Given an array of integers, every element appears twice except for one. Find that single one. No ...
- 【Valid Sudoku】cpp
题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...
- 【Next Permutation】cpp
题目: Implement next permutation, which rearranges numbers into the lexicographically next greater per ...
- 【Permutations II】cpp
题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...
随机推荐
- MySQL安装图文教程
下载 1.下载地址: http://www.mysql.com/downloads/ 2.下载图解 下载社区版本就可以,社区版里有我们的想要的几乎全部功能.只不过 商业版的mysql会提供一定高级的解 ...
- c#中判断对象为空的几种方式(字符串等)
(1)先了解几个与空类型相关的关键字和对象 Null : 关键字表示不引用任何对象的空引用,它是所有引用类型变量的默认值,在2.0版本之前也就只有引用变量类型可以为null,如(string a=n ...
- Knockout.Js官网学习(event绑定、submit绑定)
event绑定 event绑定在DOM元素上添加指定的事件句柄以便元素被触发的时候执行定义的JavaScript 函数.大部分情况下是用在keypress,mouseover和mouseout上. 简 ...
- dirname(__FILE__)与__DIR__全等
小例子如下: <?php$the_full_name = __FILE__;$the_file = dirname(__FILE__);echo $the_full_name.'<br/& ...
- 什么是PHP魔术引号
今天在读EcShop的源码中发现里面有几个地方涉及到了PHP魔术引号,之前也碰到过都忽略过去了,再次碰到该深入的理解,虽然自PHP 5.3.0 起魔术引号被废弃废弃并将自 PHP 5.4.0 起移除, ...
- C++12!配对
题目内容:找出输入数据中所有两两相乘的积为12!的对数. 输入描述:输入数据中含有一些整数n(1<=n<232). 输出描述:输出所有两两相乘的积为12!的对数. 题目分析:对于输入的每个 ...
- delphi 单引号在字符串中使用方法
可以看delph的帮助,里面有这个问题详细说明:A character string, also called a string literal or string constant, consist ...
- Oracle 查看相关优化器参数
select x.ksppinm name, y.ksppstvl value, y.ksppstdf isdefault, decode(bitand(y.ksppstvf, 7), 1, 'MOD ...
- rails中ActionController::InvalidAuthenticityToken解决办法
Ror代码 class FooController < ApplicationController protect_from_forgery :except => :index # you ...
- angularjs2 学习笔记(六) Form
Angular 2 Form表单 在angular2 form表单中我们需要了解表单数据绑定.数据验证.数据提交等内容,在下面的示例中并没有实际提交到后台,这部分内容在今后webapi中加以练习. 表 ...