242. Valid Anagram

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了242. Valid Anagram相关的知识,希望对你有一定的参考价值。

    /*
     * 242. Valid Anagram
     * 2016-6-18 by Mingyang
     * 1是别人建的bucket2是自己见得bucket,原理一样,更简洁
     * 特别注意人家的empty case一行代码就搞定,简单!
     */
     public boolean isAnagram1(String s, String t) {
            if (s == null || t == null || s.length() != t.length()) return false;
            int[] map = new int[26];
            for (int i = 0; i < s.length(); i++)
                map[s.charAt(i) - ‘a‘]++;
            for (int i = 0; i < t.length(); i++)
                if(--map[t.charAt(i) - ‘a‘] < 0)
                    return false;
            return true;
        }
     public boolean isAnagram2(String s, String t) {
         if (s == null || t == null || s.length() != t.length()) return false;
            int[] map=new int[256];
            Arrays.fill(map,0);
            for(int i=0;i<s.length();i++){
                map[s.charAt(i)]++;
            }
            for(int i=0;i<t.length();i++){
                map[t.charAt(i)]--;
                if(map[t.charAt(i)]<0)
                 return false;
            }
            return true;
        }
     /*
      * Arrays.sort(int[]) in all Java standard library implementations that I know, 
      * is an example of a comparison-based sort and thus must have worst-case complexity Ω(n log n). 
      * In particular, Oracle Java 7 uses a dual-pivot quicksort variant for the integer overloads,
      *  which actually has an Ω(n2) worst case.
      */
    public static boolean isAnagram(String a, String b) {
        char[] aa = a.toCharArray();
        char[] bb = b.toCharArray();
        Arrays.sort(aa);
        String a1 = new String(aa);
        Arrays.sort(bb);
        String b1 = new String(bb);
        if (a1.equals(b1))
            return true;
        else
            return false;
    }

 

以上是关于242. Valid Anagram的主要内容,如果未能解决你的问题,请参考以下文章

242. Valid Anagram

242. Valid Anagram

242. Valid Anagram

242 Valid Anagram

242. Valid Anagram

242. Valid Anagram