admin管理员组文章数量:1636924
题目
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;
}
};
版权声明:本文标题:28. Implement strStr() 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1729233524a1191729.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论