top of page
Writer's picturePrateek Chauhan

String Manipulation | Alternating Characters

In this blog we are discussing about alternating character problem posted on HackerRank.


Problem Statement:

You are given a string containing characters A and B 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 s = AABAAB , remove an A at positions 0 and 3 to make s = ABAB in 2 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 q, the number of queries. The next q lines each contain a string s.


Constraints:

  • 1 <= q <= 10

  • 1 <= | s | <= 10^5

  • Each string will consist only of characters A and B


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.

        AAAA -> A (3 deletions)
        BBBBB -> B (4 deletions)
      ABABABAB -> ABABABAB (0 deletions)
        BABABA -> BABABA (0 deletions)
         AAABBB -> AB (4 deletions)
 

Implementation Using Java:

import java.util.*;
import java.io.*;
public class Main
{
    static int alternatingCharacters(String s) {
        int count = 0;

        for(int i = 0; i< s.length() - 1; i++)
        {
            if(s.charAt(i) == s.charAt(i+1))
            {
                count++;
            }
        }
        return count;
    }
    private static final Scanner scanner = new Scanner(System.in);
	public static void main(String[] args) {
		
        int q = scanner.nextInt();
        
        for (int qItr = 0; qItr < q; qItr++) {
            String s = scanner.nextLine();

            int result = alternatingCharacters(s);

           System.out.println(result);
        }
        scanner.close();
    }
}
Output:
5
AAAA
3
BBBB
3
ABABAB
0
AABBAABB
4
ABBAABB
3
 

Happy Coding!


Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

 

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem

Follow Programmers Door for more.


22 views0 comments

Recent Posts

See All

Comments


bottom of page