Identify an anagram

0

I'm doing an exercise and I need to identify an anagram. More or less I have it, but it fails me, because I do not correctly identify the capitals of the lowercase letters and this I do not know very well how to do it.

I have defined a method to put the word to analyze in a TreeMap and in this way I know the letters of the word and the number of times it contains that letter, and so I have it sorted to be able to compare with other words, but It fails me, because it adds quantity regardless of whether the letter is uppercase or lowercase.

The code is

    static TreeMap getTreemap(String a){
    TreeMap<Character, Integer> mapa = new TreeMap<>();
    for (int i = 0;i<a.length(); i++){
        Integer valor = mapa.get(a.charAt(i));
        if (valor != null){
            mapa.put(a.charAt(i), valor+1);
        }else{
            mapa.put(a.charAt(i), 1);
        }
    }
    return mapa;

}

my problem may come next, when I compare the words here.

        if (mapaA.equals(mapaB) != true){
        return false;
    }else{
        return true;
    }

Since it tells me that both are equal, although they do not match uppercase or lowercase. Any suggestions to fix it? Thanks.

    
asked by pitiklan 29.12.2016 в 15:42
source

3 answers

3

You can look at this alternative

    public static boolean esAnagrama(String s1, String s2) {

        char[] array1 = s1.toCharArray();
        char[] array2 = s2.toCharArray();

        Arrays.sort(array1);
        Arrays.sort(array2);
        return new String(array1).equals(new String(array2));
    }
    
answered by 29.12.2016 / 19:43
source
1

Finally I have solved it in the following way.

Instead of working with Character, I decided to move to String and thus be able to use the String.CASE_INSENSITIVE_ORDER constant. In this way, it differentiates between uppercase and lowercase. I have not found how to do it with Chars, but this mode has seemed much more elegant to me.).

The code stays like this.

    static TreeMap getTreemap(String a){
    TreeMap<String, Integer> mapa = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    for (int i = 0;i<a.length(); i++){
        Integer valor = mapa.get(a.charAt(i)+"");
        if (valor != null){
            mapa.put(a.charAt(i)+"", valor+1);
        }else{
            mapa.put(a.charAt(i)+"", 1);
        }
    }
    return mapa;
    
answered by 29.12.2016 в 19:22
0

Try with

.compareTo()

instead of

equals ()

    
answered by 29.12.2016 в 17:21