How to get the number of characters that two strings have in common in Java

2 Answers

0 votes
import java.util.HashMap;

public class CommonCharacters {
    public static int getCommonCharacterCount(String str1, String str2) {
        HashMap<Character, Integer> charCountMap = new HashMap<>();

        // Count characters in the first string
        for (char ch : str1.toCharArray()) {
            charCountMap.put(c, charCountMap.getOrDefault(ch, 0) + 1);
        }

        int commonCount = 0;

        // Count common characters in the second string
        for (char ch : str2.toCharArray()) {
            if (charCountMap.containsKey(c) && charCountMap.get(c) > 0) {
                commonCount++;
                charCountMap.put(c, charCountMap.get(ch) - 1);
            }
        }

        return commonCount;
    }

    public static void main(String[] args) {
        String str1 = "abcdefg";
        String str2 = "xayzgoe";

        System.out.println("Number of common characters: " + getCommonCharacterCount(str1, str2));
    }
}



/*
run:

Number of common characters: 3

*/

 



answered Mar 19, 2025 by avibootz
0 votes
import java.util.HashSet;
import java.util.Set;

public class CommonCharactersCount {
    public static void main(String[] args) {
        String str1 = "abcdefg";
        String str2 = "xayzgoe";

        int count = commonCharactersCount(str1, str2);
        
        System.out.println(count); 
    }

    public static int commonCharactersCount(String str1, String str2) {
        // Convert strings to sets of characters
        Set<Character> set1 = new HashSet<>();
        for (char ch : str1.toCharArray()) {
            set1.add(ch);
        }

        Set<Character> set2 = new HashSet<>();
        for (char ch : str2.toCharArray()) {
            set2.add(ch);
        }

        // Find the intersection of the two sets
        set1.retainAll(set2);

        return set1.size();
    }
}



/*
run:

3

*/



 



answered Mar 20, 2025 by avibootz
...