What is wrong with my code?


  • 0
    I

    public class Solution {
    public boolean isAnagram(String s, String t) {

        if(s.length() != t.length()) {
            return false;
        }
        if(s.length()==0 && t.length()==0) {
            return true;
        }
        HashMap<Character, Integer> sMap = new HashMap<Character, Integer>();
        HashMap<Character, Integer> tMap = new HashMap<Character, Integer>();
        for(int i=0; i<s.length(); i++) {
            if(sMap.containsKey(s.charAt(i))) {
                sMap.put(s.charAt(i), sMap.get(s.charAt(i))+1);
        }
            else {
                sMap.put(s.charAt(i), 1);
            }
        }
        
        for(int i=0; i<t.length(); i++) {
            if(tMap.containsKey(t.charAt(i))) {
                tMap.put(t.charAt(i), tMap.get(t.charAt(i))+1);
        }
            else {
                tMap.put(t.charAt(i), 1);
            }
        }
        
        if(tMap.size() != sMap.size()) {
            return false;
        }
    
        for(Character key : tMap.keySet()) {
            if(sMap.get(key) != tMap.get(key)) {
                return false;
            }
        }
        
        return true;
    }
    

    }


  • 0

    @iqus2015 Please format your cod properly using ``` and then post your question. Here is very simple solution in C++

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            int counts[26]{0};
            for(int i = 0; i < s.length(); ++i) counts[s[i]-'a']++;
            for(int i = 0; i < t.length(); ++i) counts[t[i]-'a']--;
            for(int i = 0; i < 26; ++i) if(counts[i]) return false;
            return true;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.