实现strStr
题目描述
题目分析
这个题常规解法应该是双指针,挨个来比较,但是我想更简洁一点用map来做
用map.find来查找是否存在这个元素,其实复杂度应该更高了,因为建立map和在map查找都很费时间
最后看题解还有更骚的直接用string里面的find来查找
题解代码
map解法
class Solution {
public:
int strStr(string haystack, string needle) {
map <string,int> map_ ;
for (int i = 0;i+needle.length()<=haystack.length();i++)
{
string temp = haystack.substr(i,needle.length());
if (!map_.count(temp))
map_[temp] = i ;
}
if(!needle.length())
return 0;
return map_.count(needle)?map_[needle]:-1;
}
};
string库函数一行解决
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle)==haystack.npos?-1:haystack.find(needle);
}
};
两种结果对比
快的是库函数,慢的是map