242. Valid Anagram Java Solutin

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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

 

Subscribe to see which companies asked this question

由题 只有小写字母,使用26位的数组存储每个字母个数进行比较。

 1 public class Solution {
 2     public boolean isAnagram(String s, String t) {
 3         if(s == null || t == null || s.length() != t.length())
 4             return false;
 5         int[] cmap = new int[26];
 6         for(int i=0;i<s.length();i++){
 7             cmap[s.charAt(i)-'a']++;
 8             cmap[t.charAt(i)-'a']--;
 9         }
10         for(int c : cmap){
11             if(c != 0)
12                 return false;
13         }
14         return true;
15     }
16 }

 

posted @ 2016-04-12 17:42  Miller1991  阅读(142)  评论(0编辑  收藏  举报