Alternating Characters Hackerrank problem solution

Alternating Characters Hackerrank

Shashank likes strings in which consecutive characters are different. For example, he likes ABABA, while he doesn’t like ABAA. Given a string containing characters A and B only, he wants to change it into a string he likes. To do this, he is allowed to delete the characters in the string.

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

Input Format

The first line contains an integer T, i.e. the number of test cases.
The next T lines contain a string each.

Output Format

For each test case, print the minimum number of deletions required.

Constraints

1<= T <=10 1<=length of string <= 105

Sample Input

5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB

Sample Output

3
4
0
0
4

Explanation

AAAA —–> A, 3 deletions
BBBBB —–> B, 4 deletions
ABABABAB —–> ABABABAB, 0 deletions
BABABA —–> BABABA, 0 deletions
AAABBB —–> AB, 4 deletions because to convert it to AB we need to delete 2 A’s and 2 B’s

Solution

The problem is pretty simple. One stright forward solution can be given as follows.
If there are N consecutive same character delete N-1 out of those N characters.
Which will result into a string, in which no two consecutive characters will be the same. See the implement of the setter for the more details.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int t;
    scanf("%d", &t);
    while (t--) {
        char s[100000];
        scanf("%s", s);
        char c = "";
        int count = 0;
        for (int i = 0; i < strlen(s); i++) {
            if (c != s[i]) {
                c = s[i];
            }
            else {
                count++;
            }    
        }
        printf("%d\n", count);
    }
    return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int T;
    cin>>T;
    while(T--)
    {
        string str;
        cin>>str;
        int ans = 0;
        for(int i = 0 ; i< str.length() - 1; i++)
        {
            if(str[i] == str[i+1]) // If two consecutive characters are the same, delete one of them.
                ans++;
        }
        cout<<ans<<endl;
    }
    return 0;
}
t = input()
for _ in range(t):
    s = raw_input()
    count = 0
    for i in range(1,len(s)):
        if s[i] == s[i-1]:
            count += 1
    print count

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.