Bad Runtime Solution 56ms +2O(N) Storage Java


  • 0
    P
    public boolean isAnagram(String s, String t) {
    
        if(s==null||t==null){
            return false;
        }
        int lengthS=s.length();
        int lengthT=t.length();
        if(lengthS!=lengthT){
            return false;
        }else if(lengthS==0&&lengthT==0){
            return true;
        }
        Map<Character,Integer> hs= createMap(lengthS,s);
        Map<Character,Integer> ht= createMap(lengthT,t);
        if(hs.equals(ht)){
            return true;
        }
        
        return false;
    }
    
    	    public Map<Character,Integer> createMap(int length, String str){
             Map<Character,Integer> map= new HashMap<Character,Integer>();
             int count =0;
            for(int i=0;i<length;i++){
                if(map.containsKey(str.charAt(i))){
                    count=map.get(str.charAt(i));
                    map.put(str.charAt(i),++count);
                }else{
                     map.put(str.charAt(i),1);
                }
            }
            return map;
        }

  • 0
    S
    //This gives me 7ms run time. I know it is not perfect. I saw some other said they got 3ms
    
    public class Solution {
    public boolean isAnagram(String s, String t) {
        int slen = s.length();
        int tlen = t.length();
        
        if (slen != tlen){
            return false;
        }
        
        int[] ScharTable = new int[256];
        int[] TcharTable = new int[256];
        for (int i = 0; i<256; i++){
            ScharTable[i] = 0;
            TcharTable[i] = 0;
        }
        
        for (int j = 0; j<slen; j++){
            ScharTable[s.charAt(j)]++;
            TcharTable[t.charAt(j)]++;
        }
        
        for (int k = 0; k<256; k++){
            if (ScharTable[k] != TcharTable[k]){
                return false;
            }
        }
        
        return true;
        
        
        
    }
    

    }


Log in to reply
 

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