您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: