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.

Find the minimum number of required deletions.

Example:

Input:  s="AAABBB"
Output: 4

Approach

Java


public class AlternatingCharacters {
    public static void main(String[] args) {
        String s = "AAABBB";
        int result = alternatingCharacters(s);
        System.out.println(result);

    }

    private static int alternatingCharacters(String s) {
        int res = 0;
        for (int i = 0; i < s.length() - 1; i++) {
            if ((s.charAt(i) == 'A' && s.charAt(i + 1) == 'A'
                || (s.charAt(i) == 'B' && s.charAt(i + 1) == 'B'))
                res++;
        }
        return res;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int alternatingCharacters(string s)
{
    int res = 0;
    for (int i = 0i < s.size() - 1i++)
    {
        if ((s[i] == 'A' && s[i + 1] == 'A') || 
              (s[i] == 'B' && s[i + 1] == 'B'))
            res++;
    }
    return res;
}

int main()
{
    string s = "AAABBB";
    int result = alternatingCharacters(s);

    cout << result << "\n";

    return 0;
}


No comments:

Post a Comment