leetcode记录 242. Valid Anagram

242. Valid Anagram

自己的思路:利用两个hashmap来记录每一个String中各个字母出现与否以及出现的次数,然后遍历map,看两个map是否匹配,如果出现不包含或者出现次数不匹配的情况则返回false。

public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        Map<String,Integer> anaMaps = new HashMap();
        Map<String,Integer> anaMapt = new HashMap();
        
        for(int i=0;i<s.length();i++){
            if(anaMaps.containsKey(""+s.charAt(i))){
                int value = anaMaps.get(""+s.charAt(i));
                anaMaps.put(""+s.charAt(i),++value);
            }
            else
                anaMaps.put(""+s.charAt(i),0);
        }
        for(int i=0;i<t.length();i++){
            if(anaMapt.containsKey(""+t.charAt(i))){
                int value = anaMapt.get(""+t.charAt(i));
                anaMapt.put(""+t.charAt(i),++value);
            }
            else
                anaMapt.put(""+t.charAt(i),0);
        }
        Iterator iter = anaMaps.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String)entry.getKey();
            int val = (int)entry.getValue();
            if(!anaMapt.containsKey(key)||val!=(int)anaMapt.get(key))
                return false;
        }
        return true;
    }
}

效率不是很高!!

看别人代码:

public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
        return false;
        char [] S =s.toCharArray();
        char [] T =t.toCharArray();
        Arrays.sort(S);
        Arrays.sort(T);
        String news = new String(S);
        String newt = new String(T);
        if(news.compareTo(newt)==0)
        return true;
        else
        return false;
    }
}
public class Solution {

public boolean isAnagram(String s, String t) {

    int[] charsMap = new int['z'-'a'+1];

    for(char c: s.toCharArray()) {
        int pos = c - 'a';
        charsMap[pos]++;
    }

    for(char c: t.toCharArray()) {
        int pos = c - 'a';
        charsMap[pos]--;
    }

    for(int count: charsMap) {
        if(count != 0) {
            return false;
        }
    }

    return true;
}
}





你可能感兴趣的:(leetcode记录 242. Valid Anagram)