Skip to content

Instantly share code, notes, and snippets.

@qiaoxu123
Last active March 1, 2019 00:44
Show Gist options
  • Save qiaoxu123/b51074a969208343dd5b2177915e3bf5 to your computer and use it in GitHub Desktop.
Save qiaoxu123/b51074a969208343dd5b2177915e3bf5 to your computer and use it in GitHub Desktop.
> 字符串查找匹配题目,数据结构字符串章节本科时候讲过该题目 - 第一种方法是循环匹配,如果不相同就调一位继续全部匹配。效率非常低 - 第二种方法是,当发现不匹配后,不再从头开始继续匹配,而是从原有字符串中找到首字符相同的进行匹配。 - 第三种是参考答案,思路基本相同,但是精简了计算,效率猛增
//Runtime: 1632 ms, faster than 5.88%
//Memory Usage: 9.6 MB, less than 26.21%
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.length() == 0) return 0;
int res;
for(int i = 0;i < haystack.length();++i){
int j = 0;
res = i;
while(haystack[i] == needle[j]){
// cout << "i = " << i << " " << "j = " << j << endl;
j++;i++;
if(j == needle.length())
return i - needle.length();
}
i = res;
}
return -1;
}
};
//Runtime: 2708 ms, faster than 5.01%
//Memory Usage: 9.6 MB, less than 38.45%
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.length() == 0) return 0;
int res;
for(int i = 0;i < haystack.length();++i){
int j = 0;
res = i;
bool m = true;
while(haystack[i] == needle[j]){
cout << "i = " << i << " " << "j = " << j << endl;
j++;i++;
if(haystack[res] == haystack[i] && m == true){
res = i - 1;
m = false;
}
if(j == needle.length())
return i - needle.length();
}
i = res;
}
return -1;
}
};
//Runtime: 8 ms, faster than 99.35%
//Memory Usage: 9.5 MB, less than 42.72%
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size(),n = needle.size();
for(int i = 0;i <= m -n;i++){
int j = 0;
for(;j < n;j++){
if(haystack[i + j] != needle[j])
break;
}
if(j == n)
return i;
}
return -1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment