Alternating Characters



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 lines q each contain a string s.
Constraints
  • 1 <= q <= 10
  • 1 <= |s| <= 105
  • Each string s 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


image
The characters marked red are the ones that can be deleted so that the string doesn't have matching consecutive characters.
static int alternatingCharacters(String s) {
    if (s== null || s.isEmpty())
        return 0;
    int deletionCount = 0;
    int lastChar = s.charAt(0);
    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == lastChar)
            deletionCount++;
        else
            lastChar = s.charAt(i);
    }
    return deletionCount;
}
It's a really easy problem where we have to just remember the last character and if the next character is the same then remove it and increment delete counter otherwise update the last character.

Comments

Popular posts from this blog

Recursion

Stack

Data Structure & Algorithm