Two Characters

  • + 0 comments

    Python

    # uses letter1 and letter2 as the combo letters
    # returns length of longest alternating str with them, 0 if not possible
    def getcombolength(s, letter1, letter2):
        count = 0
        toggleletter = '?'
        for letter in s:
            if letter == letter1 or letter == letter2:
                if letter == toggleletter:
                    return 0
                count += 1
                toggleletter = letter
        return count
    
    def alternate(s):
        if len(s) <= 1:
            return 0
        letters = 'abcdefghijklmnopqrstuvwxyz'
        maxcombo = 0
        for (letter1, letter2) in [(letters[j], letters[k]) for j in range(26) for k in range(j+1, 26)]:
            combo = getcombolength(s, letter1, letter2)
            maxcombo = max(combo, maxcombo)
        return maxcombo