HACKER RANK Algorithm Strings Challenges - Alternating Characters Solution.'C++'

Algorithm Strings Challenges - Alternating Characters Solution
Problem Statement
Shashank likes strings in which consecutive characters are different. For example, he likesABABA, 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
1T10
1 length of string 105
Sample Input
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Sample Output
3
4
0
0
4
Explanation
AAAA  A3 deletions
BBBBB  B4 deletions
ABABABAB  ABABABAB0 deletions
BABABA  BABABA0 deletions
AAABBB  AB4 deletions because to convert it to AB we need to delete 2 A's and 2 B's

Solution:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
     int t;
    cin>>t;
    while(t--)
        {
        string a;
        cin>>a;
        int l=(int)a.size();
        int k=0,c=0;
        for(int i=0;i<l;i++)
            {
                if(i==0||a[i]==a[i-1])
                    k++;
            else
                {
                if(k>1)
                    {
                    c+=k-1;
                }
                k=1;
            }
        }
        if(k>1)
            {
            c+=k-1;
        }
        cout<<c<<endl;
    }
    
    return 0;
}

Thanks for Visiting, Hope this helps you....

Copyright © 2015 HackerRank.
All Rights Reserved

Comments

Popular Posts