[C++]Implement strStr() 找到子字符串第一次出现的位置
2015-08-23 20:14
405 查看
leetcode 原题链接:https://leetcode.com/problems/implement-strstr/
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
简要翻译:要求实现strStr()函数。
返回在子字符串needle在字符串haystack中第一次出现的位置,如果没有找到则返回-1;
简要分析:此题不难,我采用的是比较普遍的做法,即依依去对比字符串是否完全相同;此种做法的思路比较简单,但是时间复杂度较高,为O(mn)。
需要注意的是,空字符串也算一个子串。
实现代码:
<span style="font-size:14px;">class Solution
{
public:
int strStr(string haystack, string needle)
{
if (haystack.size() < 0)
return -1;
if (needle.size() == 0)
return 0;
int j = 0;
//cout << haystack.size() << " " << needle.size() << " " << endl;
//int lenght = haystack.size() - needle.size() + 1;
for (int i = 0; i < (int)(haystack.size() - needle.size() + 1); i++)
{
cout << "i = " << i << endl;
if (haystack[i] == needle[j])
{
int k = i;
for (; j < needle.size(); j++)
{
if (haystack[k] == needle[j])
{
k++;
} else
{
j
4000
= 0;
break;
}
}
if (j == needle.size())
{
return i;
}
}
}
return -1;
}
};</span>
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
简要翻译:要求实现strStr()函数。
返回在子字符串needle在字符串haystack中第一次出现的位置,如果没有找到则返回-1;
简要分析:此题不难,我采用的是比较普遍的做法,即依依去对比字符串是否完全相同;此种做法的思路比较简单,但是时间复杂度较高,为O(mn)。
需要注意的是,空字符串也算一个子串。
实现代码:
<span style="font-size:14px;">class Solution
{
public:
int strStr(string haystack, string needle)
{
if (haystack.size() < 0)
return -1;
if (needle.size() == 0)
return 0;
int j = 0;
//cout << haystack.size() << " " << needle.size() << " " << endl;
//int lenght = haystack.size() - needle.size() + 1;
for (int i = 0; i < (int)(haystack.size() - needle.size() + 1); i++)
{
cout << "i = " << i << endl;
if (haystack[i] == needle[j])
{
int k = i;
for (; j < needle.size(); j++)
{
if (haystack[k] == needle[j])
{
k++;
} else
{
j
4000
= 0;
break;
}
}
if (j == needle.size())
{
return i;
}
}
}
return -1;
}
};</span>
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- 关于指针的一些事情
- android上改变listView的选中颜色
- String.intern
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Mootools 1.2教程 函数
- autoit InputBox 函数
- 动易2006序列号破解算法公布
- 文件遍历排序函数
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- Oracle 函数大全[字符串函数,数学函数,日期函数]第1/4页
- Ruby实现的矩阵连乘算法
- ASP下经常用的字符串等函数参考资料
- PostgreSQL教程(五):函数和操作符详解(1)
- C#插入法排序算法实例分析