Sherlock and the Valid String

  • + 0 comments

    Python:

    def isValid(s):
        Dict = createFirstDict(s)
        Dict2 = createSecondDict(Dict)
        res = determineIfIsValid(Dict2)
        return res
        
    def createFirstDict(s):
        res = {}
        for ch in s:
            if ch not in res:
                res[ch] = 1
            else:
                res[ch] +=1
                
        return res
    
    def createSecondDict(Dict):
        res = {}
        for key1 in Dict:
             if Dict[key1] not in res:
                res[Dict[key1]] = 1
             else:
                res[Dict[key1]] += 1
                
        return res
        
    def determineIfIsValid(Dict2):
        if len(Dict2) == 1:
            return "YES"
        elif len(Dict2) > 2:
            return "NO"
        else:
            keyList = list(Dict2.keys())
            key1 = keyList[0]
            key2 = keyList[1]
            value1 = Dict2[key1]
            value2 = Dict2[key2]
            maxKey = max(key1, key2)
            minKey = min(key1, key2)
            if maxKey - minKey == 1 and Dict2[maxKey] == 1:
                return "YES"
            elif key1 == value1 == 1 or key2 == value2 == 1:
    				
                return "YES"
            
        return "NO"