Hackerrank - Alternating Characters Solution
1 min read

Hackerrank - Alternating Characters Solution

Hackerrank - Alternating Characters Solution

You are given a string containing characters  and  only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.

Your task is to find the minimum number of required deletions.

For example, given the string , remove an  at positions  and  to make  in  deletions.

Function Description

Complete the alternatingCharacters function in the editor below. It must return an integer representing the minimum number of deletions to make the alternating string.

alternatingCharacters has the following parameter(s):

  • s: a string

Input Format

The first line contains an integer , the number of queries.
The next  lines each contain a string .

Constraints

  • Each string  will consist only of characters  and

Output Format

For each query, print the minimum number of deletions required on a new line.

Sample Input

5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB

Sample Output

3
4
0
0
4

Explanation

The characters marked red are the ones that can be deleted so that the string doesn't have matching consecutive characters.

image

Solution in Python

def alternatingCharacters(s):
    a,b = "", ""
    for i in s:
        if b!=i: a+=i
        b=i
    return len(s)-len(a)
for _ in range(int(input())):
    print(alternatingCharacters(input()))

Using regex

import re
def alternatingCharacters(s):
    return len(s)-len(re.sub(r"([AB])\1+",lambda x: x.groups()[0], s))
for _ in range(int(input())):
    print(alternatingCharacters(input()))

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×