242. 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.

思路:本题只需毕竟字符在两个字符串中出现次数相同,跟顺序无关系,而且都假设是lowercase下,果断祭出大杀器用char字符数组来做,假设是ASCII码开辟26空间,统计字符出现次数。 如果是Unicode则开辟256空间

public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s == null && t == null) return true;
        if (s.length() == 0 && s.length() == 0) return true;
        if (s.length() == 0 || t.length() == 0 || s == null || t == null) return false;
        char[] arr = new char[26];
        for (int i = 0; i < s.length(); i++) {
            int pos = s.charAt(i) - 'a';
            arr[pos]+=1;
        }
        for (int j = 0; j < t.length(); j++) {
            int pos = t.charAt(j) - 'a';
            arr[pos]-=1;
        }
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != 0) {
                return false;
            }
        }
        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