You are given a string of characters comprising of and . You can choose any index and change to either or .
Find the minimum number of changes that you must make to string such that the resulting string is of the following format:
where
In other words, your task is to determine the minimum number of changes such that string has number of in the beginning, followed by the remaining number of .
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 s, int 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++;} elseb++;}}if (a != 0 && b != 0)count = (a > b) ? count + b : count + a;return count;}}
No comments:
Post a Comment