Given a string str
consisting only of characters ‘A’ and ‘B’, find the absolute difference between the number of occurrences of ‘A’ and ‘B’.
Solution:
Approach:
- Initialize two counters:
countA
andcountB
to 0. - Iterate through each character in the string:
- If the character is ‘A’, increment
countA
. - If the character is ‘B’, increment
countB
.
- If the character is ‘A’, increment
- Calculate the absolute difference between
countA
andcountB
.
public class CharacterDifference {
public static int findDifference(String str) {
int countA = 0;
int countB = 0;
for (char c : str.toCharArray()) {
if (c == 'A') {
countA++;
} else if (c == 'B') {
countB++;
}
}
return Math.abs(countA - countB);
}
public static void main(String[] args) {
String str1 = "AAABAB";
String str2 = "AAAAAAAAB";
String str3 = "BB";
System.out.println(findDifference(str1)); // Output: 2
System.out.println(findDifference(str2)); // Output: 7
System.out.println(findDifference(str3)); // Output: 2
}
}