LC#242 : Valid Anagram
Leet Code Arrays HashMap

25 minutes


go back go back go back home home

LeetCode Problem #242 : Valid Anagram


Question:

question

Example 1:

Example

Constraints:

1 <= prices.length <= 105
0 <= prices[i] <= 104

Initial Solution:

your thoughts

class Solution {
    public boolean isAnagram(String s, String t) {
        HashMap<Character,Integer> count = new HashMap<>();
        for(char ch : s.toCharArray()){
            if(count.containsKey(ch)){
                count.put(ch,count.get(ch)+1);
            }else count.put(ch,1);
        }
        for(char ch : t.toCharArray()){
            if(count.containsKey(ch)){
                if(count.get(ch)-1 < 0) return false;
                count.put(ch,count.get(ch)-1);
            }else return false;
        }
        for(int size : count.values()){
            if(size > 0) return false;
        }
        return true;
    }
}

Peformance:

Very Very Bad 😔 but it passes