Arrays & Hashing

Str

Estimated reading: 1 minute 36 views

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:

  1. Initialize two counters: countA and countB to 0.
  2. Iterate through each character in the string:
    • If the character is ‘A’, increment countA.
    • If the character is ‘B’, increment countB.
  3. Calculate the absolute difference between countA and countB.
				
					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
    }
}
				
			
Share this Doc

Str

Or copy link

CONTENTS