Strings: Making Anagrams

  • + 0 comments

    Java Solution:

    public static int makeAnagram(String a, String b) {
    
    char[] firstString= a.toCharArray();
    char[] secondString= b.toCharArray();
    
    // Replace matching characters with ' ' when a match is found between the strings
    for (int i = 0; i < a.length(); i++) {
        for (int j = 0; j < b.length(); j++) {
            if(firstString[i]==secondString[j]){
                firstString[i]=' ';
                secondString[j]=' ';
                break;
            }
        }
    }
    
    // Remove all the white spaces and count the lenght of final string
    String finalStr = String.valueOf(firstString)+String.valueOf(secondString);
    finalStr = finalStr.replaceAll("\\s+", "");
    
    return finalStr.length();
    

    }