leetcode[Valid Anagram]

来源:互联网 发布:好牧人12网络牧养中心 编辑:程序博客网 时间:2024/06/10 23:54

下面这种解法对于很大数据量时会报错:

public class Solution {//字符串s的Anagram就是由字符串s的所有字符颠倒顺序产生的组合//判断字符串t是否是字符串s的Anagram//一种方式是将s的所有排列组合与t作对比,但太耗时//另一种方式是将s的所有字符用一个散列表来统计,同时将t的所有字符用散列表来统计,二者相比较    public boolean isAnagram(String s, String t) {        TreeMap<Character, Integer> mapS = new TreeMap<>();        TreeMap<Character, Integer> mapT = new TreeMap<>();        //统计两个字符串的散列表        for(int i = 0; i < s.length(); i++){        if(mapS.containsKey(s.charAt(i))){        mapS.put(s.charAt(i), mapS.get(s.charAt(i)) + 1);        }        else{        mapS.put(s.charAt(i), 1);        }        }        for(int i = 0; i < t.length(); i++){        if(mapT.containsKey(t.charAt(i))){        mapT.put(t.charAt(i), mapT.get(t.charAt(i)) + 1);        }        else{        mapT.put(t.charAt(i), 1);        }        }        //比较两个字符串的散列表是否相同        if(mapS.keySet().size() != mapT.keySet().size()){        return false;        }        else{        Iterator<Character> S = mapS.keySet().iterator();        Iterator<Character> T = mapT.keySet().iterator();        while(S.hasNext()){        char ss = S.next();        char tt = T.next();        if(ss != tt){        return false;        }        else{        if(mapS.get(ss) != mapT.get(tt)){        return false;        }        }        }        }        return true;    }}

正解一(排序):

public class Solution {    public boolean isAnagram(String s, String t) {    char[] as = s.toCharArray();    char[] at = t.toCharArray();    Arrays.sort(as);    Arrays.sort(at);        String s1 = new String(as);    String s2 = new String(at);    if(s1.equals(s2)){    return true;    }    else{    return false;    }    }}

正解二:

public class Solution {//既然题目中说了字符串s和t都是由小写字母组成的,那么自己写一个散列表(用数组实现)来比较,对于大数据量出错的问题就解决了    public boolean isAnagram(String s, String t) {    int[] as = new int[26];//小写字母a代表0,依次类推    int[] at = new int[26];    for(int i = 0; i < 26; i++){    as[i] = 0;    at[i] = 0;    }    //构造字符串s和t的散列表    for(int i = 0; i < s.length(); i++){    as[s.charAt(i) - 'a']++;    }    for(int i = 0; i < t.length(); i++){    at[t.charAt(i) - 'a']++;    }    //比较两个散列表    for(int i = 0; i < 26; i++){    if(as[i] != at[i]){    return false;    }    }    return true;    }}

正解二的一个改进:

public class Solution {    public boolean isAnagram(String s, String t) {        int[] alphabet = new int[26];        for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++;        for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--;        for (int i : alphabet) if (i != 0) return false;        return true;    }}