Sherlock and the Valid String

  • + 0 comments
    def isValid(s):
        arr = [0] * 26
        for i in range(len(s)):
            arr[ord(s[i])-97]+=1
        arr.sort(reverse=True)
        if min(arr) == 0:
            arr= arr[:arr.index(0)]
        if len(arr) == 1:
            return "YES"
        mainValue = arr[1]
        firstValue = arr[0]
        lastValue = arr[-1]
        left = CheckIsAllSame(arr[0:len(arr)-1])
        if left and (lastValue == mainValue or lastValue == 1):
            return "YES"
        right = CheckIsAllSame(arr[1:len(arr)])
        if right and (firstValue == mainValue or firstValue == mainValue + 1):
            return "YES"
        return "NO"
    
    def CheckIsAllSame(arr):
        for i in range(len(arr)-1):
            if arr[i] != arr[i+1]:
                return False
        return True