lintcode-easy-Two Strings Are Annagrams

Write a method anagram(s,t) to decide if two strings are anagrams or not.

Given s="abcd"t="dcab", return true.

public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        // write your code here
        if(s == null && t == null)
            return true;
        if(s == null || t == null)
            return false;
        
        int length1 = s.length();
        int length2 = t.length();
        
        if(length1 != length2)
            return false;
        
        int[] ch = new int[128];
        
        for(int i = 0; i < length1; i++){
            ch[s.charAt(i)]++;
        }
        for(int i = 0; i < length1; i++){
            ch[t.charAt(i)]--;
        }
        for(int i = 0; i < 128; i++){
            if(ch[i] != 0)
                return false;
        }
        
        return true;
    }
};

 

posted @ 2016-03-09 08:38  哥布林工程师  阅读(169)  评论(0编辑  收藏  举报