Imple
ment strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
解题:
要考虑“”,""情况,输出为0
最初的写法,暴力法:
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.length() == 0) {
if(haystack.length() == 0)return 0;
return -1;
}
for(int i =0;i<=haystack.length()-needle.length();i++){
if(haystack.at(i)==needle.at(0)){
int y = i;
int equation = 0;
for(int j = 0;j<needle.length();j++,y++){
if(haystack.at(y)!=needle.at(j)){
equation = 1;
break;
}
}
if(!equation){
return i;
}
}
}
return -1;
}
};
超时
然后:
这道题的直接思路就是暴力查找,就是一个字符一个字符地进行匹配。不多说了,如果有兴趣,可以去研究这几个O(m+n)的算法:Rabin-Karp算法、KMP算法和Boyer-Moore算法。
时间复杂度:O(mn)
空间复杂度:O(1)
#include <iostream> using namespace std;class Solution {public: int strStr(string haystack, string needle) { if(haystack.length()<needle.length())return -1;//没有此句,会超时 unsigned long al = haystack.length(); unsigned long bl = needle.length(); for(int i =0,j;i<=al-bl;i++){ for( j = 0;j<needle.length()&&haystack.at(i+j)==needle.at(j);j++); if(j==bl){ return i; } } return -1; } };int main(int argc, const char * argv[]) { Solution c; string a; string b; while (1) { cout<<"start"<<endl; cin>>a; cin>>b; cout<<c.strStr(a, b)<<endl; } return 0;}