Thanks for any hint to my solution of 642. My question focuses on the self compare function as follow.
struct Mycompare {
bool operator()(const MyType &A, const MyType &B) const {
if (0) {
return A.first > B.first || (A.first == B.first && A.second < B.second);
} else {
if (A.first == B.first) {
A.second < B.second;
}
return A.first > B.first;
}
}
};In leetcode, when the "if" branch is enable, my solution will pass. However, my solution will fail when the "else" branch is enable. The input and output is as follow
Input:
["AutocompleteSystem","input","input","input","input"]
[[["i love you","island","iroman","i love leetcode"],[5,3,2,2]],["i"],[" "],["a"],["#"]]
Output:
[null,["i love you","island","iroman"],["i love you","i love leetcode"],[],[]]
Expected:
[null,["i love you","island","i love leetcode"],["i love you","i love leetcode"],[],[]]While in visual studio, my solution with either the "if" branch or "else" branch output the expected output. Could some one point out my problem? I apprecaite.
The complete code is as follow:
class AutocompleteSystem {
public:
//frequency is the label in the small heap
#define MyType pair<int, string>
bool isPrefix(string &A, string &B) {
if (A.size() < B.size()) {
return false;
}
else {
// I didn't consider the empty case
int lhs = 0, rhs = 0;
while (rhs < B.size()) {
if (A[lhs] != B[rhs]) return false;
lhs++;
rhs++;
}
return true;
}
}
void addToDict(MyType &A) {
dict.push(A);
if (dict.size() > k) {
dict.pop();
}
}
struct Mycompare {
bool operator()(const MyType &A, const MyType &B) const {
if (0) {
return A.first > B.first || (A.first == B.first && A.second < B.second);
} else {
if (A.first == B.first) {
A.second < B.second;
}
return A.first > B.first;
}
}
};
AutocompleteSystem(vector<string> sentences, vector<int> times) {
k = 3;
for (int i = 0; i < sentences.size(); ++i) {
mapper[sentences[i]] = times[i];//keep the mapping
}
}
vector<string> input(char c) {
vector<string> rst;
if (c == '#') {
// keep the search sentence
mapper[cur]++;
// clear process
cur.clear();
//dict = priority_queue<MyType, vector<MyType>>();// maybe we can remove this since we have pop the data
return rst;
}
else {
cur.push_back(c);//append to the previous string
MyType candi;
for (auto i : mapper) {
candi = MyType(i.second, i.first);
if (isPrefix(candi.second, cur)) {
addToDict(candi);
}
}
// add to the rst vcector
while (dict.size()) {
// each top value is the smallest one
rst.insert(rst.begin(), dict.top().second);
dict.pop();
}
return rst;
}
}
int k;// the capacity of dict
string cur;//keep the input string; make sure to clean it when '#' is detected
unordered_map<string, int> mapper;// keep the mapping of sentence <--> frequency; could be optimized by using Trie
priority_queue<MyType, vector<MyType>, Mycompare> dict;
};