Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.

public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s == null && t == null)
            return true; 
        if ((s == null && t != null) || (s != null && t == null))
            return false; 
        if (s.length() != t.length())
            return false; 
        
        int[] a = new int[128]; 
        int[] b = new int[128]; 
        
        for (int i = 0; i < s.length(); i++) {
            a[s.charAt(i)] ++; 
            b[t.charAt(i)] ++;
            
        }
        for (int i = 0; i < 128; i++) {
            if (a[i] != b[i]) 
                return false;
            else 
                continue;
        }
         
        return true;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s