classTrie { public: /** Initialize your data structure here. */ structNode{ bool flag; Node* next[26]; Node(){ for(int i = 0; i < 26; i++) next[i] = NULL; flag = false; } }; Node* root; Trie() { root = newNode(); } /** Inserts a word into the trie. */ voidinsert(string word){ Node* cur = root; for(int i = 0; i < word.size(); i++){ if(cur->next[word[i]-'a'] == NULL) cur->next[word[i]-'a'] = newNode(); cur = cur->next[word[i]-'a']; } cur->flag = true; } /** Returns if the word is in the trie. */ boolsearch(string word){ Node* cur = root; for(int i = 0; i < word.size(); i++){ if(cur->next[word[i]-'a'] == NULL) returnfalse; cur = cur->next[word[i]-'a']; } return cur->flag; } /** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ Node* cur = root; for(int i = 0; i < prefix.size(); i++){ if(cur->next[prefix[i]-'a'] == NULL) returnfalse; cur = cur->next[prefix[i]-'a']; } returntrue; } };
/** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
classUndergroundSystem { public: // startStation endStation, time, cnt map<pair<string, string>, pair<int, int>> record; // user id, startStation, startTime; map<int, pair<string, int> > running; UndergroundSystem() { record.clear(); running.clear(); } voidcheckIn(int id, string stationName, int t){ running[id] = make_pair(stationName, t); } voidcheckOut(int id, string stationName, int t){ auto it = running.find(id); record[make_pair(it->second.first, stationName)].first += (t - it->second.second); record[make_pair(it->second.first, stationName)].second++; running.erase(it); } doublegetAverageTime(string startStation, string endStation){ double time = (double) record[make_pair(startStation, endStation)].first; int cnt = record[make_pair(startStation, endStation)].second; return time / cnt; } };
/** * Your UndergroundSystem object will be instantiated and called as such: * UndergroundSystem* obj = new UndergroundSystem(); * obj->checkIn(id,stationName,t); * obj->checkOut(id,stationName,t); * double param_3 = obj->getAverageTime(startStation,endStation); */