Changes in a string

You are given a string S of N characters comprising of As and Bs. You can choose any index i and change Si to either A or B.

Find the minimum number of changes that you must make to string S such that the resulting string is of the following format:

 AAAA........x number of AsBBBB........nx number of Bs       

where 0xn

In other words, your task is to determine the minimum number of changes such that string S has x number of As in the beginning, followed by the remaining (nx) number of Bs.

Example:

Input: n=4, str="BABA"
Output: 2

Approach

Java


public class ChangesInstring {

    public static void main(String args[]) throws Exception {
        int n = 4;
        String str = "BABA";
        int ans = check(str, str.length());
        System.out.println(ans);
    }

    static int check(String sint n) {
        int count = 0, a = 0, b = 0;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == 'A') {
                a++;
                if (b != 0 && a > b) {
                    count += b;
                    a += b;
                    b = 0;
                }
            } else {
                if (b == 0) {
                    a = 0;
                    b++;
                } else
                    b++;
            }
        }
        if (a != 0 && b != 0)
            count = (a > b) ? count + b : count + a;
        return count;
    }
}


No comments:

Post a Comment