Given two strings s and t , write a function to determine if t is an anagram of s.git
Example 1:github
Input: s = "anagram", t = "nagaram" Output: true
Example 2:數組
Input: s = "rat", t = "car" Output: false
Note:
You may assume the string contains only lowercase alphabets.code
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?排序
//若是是使用map 也是一樣的效果 都是"桶" public static boolean isAnagram(String s, String t) { int[] alphabet = new int[26]; for (int i = 0; i < s.length(); i++) { alphabet[s.charAt(i) - 'a']++; } for (int i = 0; i < t.length(); i++) { alphabet[t.charAt(i) - 'a']--; } for (int i : alphabet) { if (i != 0) { return false; } } return true; }
//這是對字符數組 作了一個排序 而後比較 public static boolean isAnagram2(String s, String t) { char[] sChar = s.toCharArray(); char[] tChar = t.toCharArray(); Arrays.sort(sChar); Arrays.sort(tChar); return Arrays.equals(sChar, tChar); }
git:https://github.com/woshiyexinjie/leetcode-xinleetcode