Alternating Characters

  • + 0 comments
    def alternatingCharacters(s):
        b_s=s.split('A')
        a_s=s.split('B')
        print(a_s,b_s)
        ans=0
        for i in a_s:
            if 'A' in i :
                ans+=(len(i)-1)
        for j in b_s:
            if 'B' in j :
                ans+=(len(j)-1)
        return ans
    

    optimized version below

    def alternatingCharacters(s):
        deletions = 0 
        for i in range(1, len(s)):  
            if s[i] == s[i - 1]:  
                deletions += 1 
        return deletions