My Java solution using hashset


  • -1
    J
    public int sumChar(String s){
    	int sum=0;
    	for(int i=0;i<s.length();i++){
    		int temp=s.charAt(i);
    		sum=sum+temp;
    	}
    	return sum;
    }
    public boolean isAnagram(String s,String t){
    	HashSet<Character> aa=new HashSet<Character>();
    	HashSet<Character> bb=new HashSet<Character>();
    	char[] ss=s.toCharArray();
    	char[] tt=t.toCharArray();
    	if(ss.length!=tt.length){
    		return false;
    	}
    	if(sumChar(s)!=sumChar(t)){
    		return false;
    	}
    	for(int i=0;i<ss.length;i++){
    		aa.add(ss[i]);
    		bb.add(tt[i]);
    	}
    	for(int i=0;i<tt.length;i++){
    		if(aa.contains(tt[i])){
    			aa.remove(tt[i]);
    			bb.remove(tt[i]);
    		}else{
    			continue;
    		}
    	}
    	if(aa.size()==0&&bb.size()==0){
    		return true;
    	}
    	return false;
    }

  • 0
    Q

    That sumChar() function hack idea is really ugly.
    For example it will return true for "abbccd" and "aabcdd"


  • 0
    J

    sumChar() function is just used as one piece of judge condition


  • 0
    Q

    All of your pieces is not enough...


  • 0
    J

    I'd like to hear~


  • 0
    Q

    isAnagram("abbccd", "aabcdd") will return true instead of false.


  • 0
    J

    yeah its true, any Idea how could I fix this? seems like I've picked a wrong angle to solve this


  • 0
    Q

    Set is a wrong collection to use. You need to be able to handle multiples of the same character. There are plenty of solutions already submitted.


  • 0
    J

    Thx for the advice~~


Log in to reply
 

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