问题
My confusion comes from a solution for problem 792. Number of Matching Subsequences
in leetcode, the naive solution is to check all characters in S for each searching word.
The time complexity is too high to pass all test cases as outlined in the official answer.
The first code piece listed below could beats 100% merely because it calls string::find_first_of
function, while my hand written codes uses exactly the same routine(I believe) get TLE as expected.
So, why the first one is so fast?
// comes from the second solution post in leetcode-cn
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
int res = 0, j;
for (int i = 0; i < words.size(); i ++) {
int position = -1;
for (j = 0; j < words[i].size(); j ++) {
position = S.find_first_of(words[i][j], position + 1);
if (position == -1) break;
}
if (j == words[i].length()) res ++;
}
return res;
}
};
version 2 hand written Time limit exceed
static inline int find_first_of(const string & s, char & c, int st) {
int n = s.size() - st;
const char * data = s.data(), * cur = data + st;
for (std::size_t i = 0; i < n; ++i) {
if (cur[i] == c)
return cur + i - data;
}
return -1;
}
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
int res = 0, j;
for (int i = 0; i < words.size(); i ++) {
int position = -1;
for (j = 0; j < words[i].size(); j ++) {
position = find_first_of(S, words[i][j], position + 1);
if (position == -1) break;
}
if (j == words[i].length()) res ++;
}
return res;
}
};
来源:https://stackoverflow.com/questions/63049548/implementation-of-stringfind-first-of