[leetcode]Implement strStr()
来源:互联网 发布:全球地区数据库 编辑:程序博客网 时间:2024/06/06 13:16
Implement strStr()
Total Accepted: 48184 Total Submissions: 218379My SubmissionsImplement 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.
笨办法,从开头检查到尾,
O(nm) runtime, O(1) space
改进的方法应该是O(n),前面转载了一个博客,有更好的方法。
// test28ImplementstrStr.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "string"
using std::string;
int strStr(string haystack, string needle);
int _tmain(int argc, _TCHAR* argv[])
{
string s1 = "haha";
string s2 = "jhajdfhahhha";
int i = strStr(s2, s1);
return 0;
}
int strStr(string haystack, string needle)
{
int num1 = haystack.size();
int num2 = needle.size();
if (num1 < num2)
return -1;
if (num2 == 0)
return 0;
for (int i = 0; i <= num1 - num2; i++)
{
if (haystack[i] == needle[0])
{
string temp(haystack,i,num2);
if (temp==needle)
return i;
}
}
return -1;
}
//
#include "stdafx.h"
#include "string"
using std::string;
int strStr(string haystack, string needle);
int _tmain(int argc, _TCHAR* argv[])
{
string s1 = "haha";
string s2 = "jhajdfhahhha";
int i = strStr(s2, s1);
return 0;
}
int strStr(string haystack, string needle)
{
int num1 = haystack.size();
int num2 = needle.size();
if (num1 < num2)
return -1;
if (num2 == 0)
return 0;
for (int i = 0; i <= num1 - num2; i++)
{
if (haystack[i] == needle[0])
{
string temp(haystack,i,num2);
if (temp==needle)
return i;
}
}
return -1;
}
0 0
- LeetCode: Implement strStr()
- [Leetcode] Implement strstr()
- Leetcode: Implement strStr
- [Leetcode] Implement strStr()
- LeetCode Implement strStr()
- 【leetcode】Implement strStr()
- [LeetCode]Implement strStr()
- [LeetCode] Implement strStr()
- [LeetCode] Implement strStr()
- LeetCode-Implement strStr()
- LeetCode: Implement strStr()
- LeetCode - Implement strStr()
- LeetCode: Implement strStr()
- 【leetcode】Implement strStr()
- Leetcode: Implement strStr()
- leetcode implement strStr
- LeetCode Implement strStr()
- LeetCode题解:Implement strStr()
- UIView控件 属性和方法详解
- 【计算机基础知识】海量字符生成与匹配实现报告
- 在Visual Studio 2010中已经找不到直接创建WebService的模板方式
- 杭电5053
- Java反射之类的实例对象的三种表示方式
- [leetcode]Implement strStr()
- 文章标题
- 共享内存shmat shmget shmdt shmctl ipcs ipcmk ipcrm
- Unity 编辑器下控制播放Animator
- python 使用raw socket进行TCP SYN扫描
- 3-17(求数组平均值)
- Android TextView内部padding问题
- poj 2505 博弈(乘以[2,9])
- 第28题