648. Unique Word Abbreviation

class ValidWordAbbr { public: /* * @param dictionary: a list of words */ //開始的時候沒有理解題意 unordered_map<string, int> m1; unordered_map<string, int> m2; ValidWordAbbr(vector<string> dictionary) { // do intialization if necessary for(int i = 0; i < dictionary.size(); i++){ string word = dictionary[i]; m1[word]++; string temp; if(word.size() > 2){ /* string temp(2, '0'); temp[0] = word[0]; temp[1] = word[word.size() - 1]; temp += to_string(word.size()); */ temp = word.front() + to_string(word.size() - 2) + word.back(); //temp = "" + word[0] + to_string(word.size() - 2) + word[word.size() - 1]; 不行 为什么? } else{ temp = word; } m2[temp]++; } } /* * @param word: a string * @return: true if its abbreviation is unique or false */ bool isUnique(string &word) { // write your code here string abbr; if(word.size() > 2){ /* string temp(2, '0'); temp[0] = word[0]; temp[1] = word[word.size() - 1]; temp += to_string(word.size()); */ abbr = word.front() + to_string(word.size() - 2) + word.back(); } else{ abbr = word; } if(m1[word] == m2[abbr]){ return true; } else{ return false; } } }; /** * Your ValidWordAbbr object will be instantiated and called as such: * ValidWordAbbr obj = new ValidWordAbbr(dictionary); * bool param = obj.isUnique(word); */

Comments

Popular posts from this blog

算法的比较