Monday 12 January 2015

Hackerrank Alternating Characters Solution

Problem Statement
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.
Next T lines contain a string each.
Output Format
Print minimum number of required steps for each test case.
Constraints
1T10
1lengthofString105 
Sample Input
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Sample Output
3
4
0
0
4
Explanation
AAAAA, 3 deletions
BBBBBB, 4 deletions
ABABABABABABABAB, 0 deletions
BABABABABABA, 0 deletions
AAABBBAB, 4 deletions
Source Code:

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


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int t;
    cin>>t;
    while(t--){
    char str[1000000];
    long  i,cnt =0,n;
    cin>>str;
    n = strlen(str);
    for(i=0;i<n-1;i++)
        {
        if(str[i]==str[i+1])
            {
            cnt++;
        }
    }
    cout<<cnt<<endl;
    }
    return 0;
}

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

0 comments:

Post a Comment