HELP::Getting memory limit exceeded for some test cases


#1
#define ALPHABET_SIZE 26
class TrieNode {
public:
TrieNode* children[ALPHABET_SIZE];
bool isEndOfWord;
static void insert(string key, TrieNode* root){
    int index;
    TrieNode* temp = new TrieNode();
    temp = root;
    for(int i = 0 ; i < key.size(); i++){
        index = key[i] - 'a';
        if(temp->children[index] == NULL){
            temp->children[index] = new TrieNode();
        }
        temp = temp->children[index];
    }
    temp->isEndOfWord = true;
}

static bool search(string key, TrieNode* root){
    int index;
    TrieNode* temp = new TrieNode();
    temp = root;
    for(int i = 0; i < key.size(); i++){
        index = key[i] - 'a';
        if(temp->children[index] == NULL) return false;
        temp = temp->children[index];
    }
    return (temp!=NULL && temp->isEndOfWord);
    
}

TrieNode(){
    this->isEndOfWord = false;
    for(int i = 0; i < ALPHABET_SIZE; i++){
        children[i] = NULL;
    }
}
};

bool compare(pair<int, int> x, pair<int, int> y){
if(x.first > y.first) return true;
else if(x.first < y.first) return false;
else return x.second < y.second;
}

vector<int> Solution::solve(string A, vector<string> &B) {
vector<pair<int, int>> v;
vector<int> ans;
int ct = 0;
string s = "";
TrieNode* root = new TrieNode();

for(int j = 0 ; j < A.size(); j++){
    if(A[j] == '_' && s != ""){
        TrieNode::insert(s, root);
        s = "";
    }
    else s += A[j];
}
if(s != "") TrieNode::insert(s, root);
for(int i = 0; i < B.size(); i++){
    ct = 0;
    s = "";
    for(int j = 0 ; j < B[i].size(); j++){
        if(B[i][j] == '_'){
            ct += TrieNode::search(s, root);
            s = "";
        }
        else s += B[i][j];
    }
    if(s != "") ct += TrieNode::search(s, root);
    
    TrieNode* root = new TrieNode();
    v.push_back({ct, i});
}
delete(root);
sort(v.begin(), v.end(), compare);
for(int i = 0; i < v.size(); i++){
    ans.push_back(v[i].second);
}
return ans;
}