My code fails at {["hello"], isUnique("hello")}, but in Xcode it works fine...


  • 0
    H

    Here is the code...probably I made some stupid mistakes here...

    class ValidWordAbbr {
    public:
    
        std::map<std::string, bool>* lookupMap;
        std::set<std::string>* dictionarySet;
        
        ValidWordAbbr(vector<string> &dictionary) {
            lookupMap = new std::map<std::string, bool>();
            dictionarySet = new std::set<std::string>(std::begin(dictionary), std::end(dictionary));
            for(std::string str : *dictionarySet)
            {
                std::string abbr = getAbbr(str);
                (*lookupMap)[abbr] = 1 - lookupMap->count(abbr);
            }
        }
    
        bool isUnique(string word) {
            std::string abbr = getAbbr(word);
            bool keyExist = lookupMap->count(abbr);
            if(keyExist)
            {
                return (*lookupMap)[abbr] && dictionarySet->count(word);
            }
            else
                return true;
        }
        
        std::string getAbbr(std::string str)
        {
            if(str.length() <= 2) return str;
            std::string newStr;
            newStr += str[0];
            newStr += std::to_string(str.length() - 2);
            newStr += str[str.length() - 1];
            return newStr;
        }
        
        ~ValidWordAbbr()
        {
            delete lookupMap;
            delete dictionarySet;
        }
    };

  • 0
    S

    I have the same problem in Python code which failed at "hello"], isUnique("hello"). It works fine in my native shell. I think the online judge system has some problem with this case.

    class ValidWordAbbr(object):
        def __init__(self, dictionary):
            """
            initialize your data structure here.
            :type dictionary: List[str]
            """
            self.d = dict()
            for i in dictionary:
                if len(i) <= 2:
                    self.d[i+'0'] = 0
                else:
                    self.d[i[0]+i[-1]+str(len(i)-2)] = 0
    
        def isUnique(self, word):
            """
            check if a word is unique.
            :type word: str
            :rtype: bool
            """
            if len(word) <= 2:
                k = word+'0'
            else:
                k = word[0] + word[-1] + str(len(word)-2)
            if k in self.d:
                return False
            else:
                return True

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.