loading...

Daily HackerRank Challenge - Day 28

wingkwong profile image Wing-Kam ・1 min read

About

This is a series of Daily HackerRank Challenge. Each day I show the some solutions written in C++.


Alternating Characters

image

Sample Input

5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB

Sample Output

3
4
0
0
4

Since we only have two different character A and B, we can take the first one as c and iterate the rest of them to compare with it. If they are same, increase the counter by 1. If not, update c to the other character.

Final Solution

int alternatingCharacters(string s) {
    int ans=0;
    char c=s[0];
    for(int i=1;i<s.size();i++){
        char cc=s[i];
        if(c==cc) ans++;
        else c=cc;
    }
    return ans;
}

Complete Code

Check out the complete code via below link

Posted on by:

wingkwong profile

Wing-Kam

@wingkwong

Consultant by day. Developer by night. AWS certified. Exploring #CloudNative currently.

Discussion

pic
Editor guide