28. Implement strStr()
2016-06-07 20:10
495 查看
题目
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
分析
从一个字符串中查找给定字符串第一次出现的位置,C++的泛型算法里面find算法只能查找给定区间的某个元素出现位置,而search算法可以查找给定区间内某一区间第一次出现的位置,即前两个参数是haystack.begin()和haystack.end(),后两个是needle.begin()和needle.end(),但是search算法略慢,最快的是使用string.find(),该函数可在当前string中查找参数第一次出现的位置,如果找不到,则返回npos,方法一使用search实现,方法二使用string的find实现。
方法一:
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.empty()&&needle.empty())
return 0;
string::iterator it=search(haystack.begin(),haystack.end(),needle.begin(),needle.end());
return it==haystack.end()?-1:it-haystack.begin();
}
};方法二:
class Solution {
public:
int strStr(string haystack, string needle) {
int ans = haystack.find(needle);
return (ans==string::npos) ? -1 : ans;
}
};
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
分析
从一个字符串中查找给定字符串第一次出现的位置,C++的泛型算法里面find算法只能查找给定区间的某个元素出现位置,而search算法可以查找给定区间内某一区间第一次出现的位置,即前两个参数是haystack.begin()和haystack.end(),后两个是needle.begin()和needle.end(),但是search算法略慢,最快的是使用string.find(),该函数可在当前string中查找参数第一次出现的位置,如果找不到,则返回npos,方法一使用search实现,方法二使用string的find实现。
方法一:
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.empty()&&needle.empty())
return 0;
string::iterator it=search(haystack.begin(),haystack.end(),needle.begin(),needle.end());
return it==haystack.end()?-1:it-haystack.begin();
}
};方法二:
class Solution {
public:
int strStr(string haystack, string needle) {
int ans = haystack.find(needle);
return (ans==string::npos) ? -1 : ans;
}
};
相关文章推荐
- Unity Shader简单Shader二
- C语言中声明与定义的意义和使用方法
- HDU 2089 不要62
- vs2005中总是保留最近打开的项目和文件的记录
- CodeForces 659 B. Qualifying Contest(结构体排序的问题)
- 关于STL中List解析
- javascritp伪协议
- Android之系统服务-WindowManager
- LVS+Keepalived负载均衡操作手册
- JDBC的简介及操作
- redis-集群重启
- JFinal - Handler 处理流程
- Bootstrap是什么,Bootstrap里的文件分别表示什么?都有什么用?
- 提供一个解决unrecognized selector错误的宏定义,所有类都不会触发unrecognized selector错误 —
- 回忆多项式解析运算思路
- filename.whl is not supported wheel on this platform
- 国美“6.18“主张新选择
- 汇编程序员之代码风格指南
- hdu3433(dp+二分)
- 乐学成语——第一部分