Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram" Output: trueExample 2:
Input: s = "rat", t = "car" Output: 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?
有效的字母异位词。题意是给两个string,请判断他们是否互为字母异位词。
这题用counting sort做,会用到hashmap。思路是建立一个hashmap,先扫描s,记录s里面每个字母出现的次数;然后遍历t的时候,减去t里面每个字符出现的次数,如果这个过程中发现t中有任何字符在hashmap里不存在,就return false。若没有,则再次遍历hashmap,如果有任何一个key的value不是0,也return false。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public boolean isAnagram(String s, String t) { 3 // corner case 4 if (s.length() != t.length()) { 5 return false; 6 } 7 8 // normal case 9 int[] count = new int[26]; 10 for (int i = 0; i < s.length(); i++) { 11 count[s.charAt(i) - 'a']++; 12 count[t.charAt(i) - 'a']--; 13 } 14 for (int j = 0; j < count.length; j++) { 15 if (count[j] != 0) { 16 return false; 17 } 18 } 19 return true; 20 } 21 }
JavaScript实现
1 /** 2 * @param {string} s 3 * @param {string} t 4 * @return {boolean} 5 */ 6 var isAnagram = function(s, t) { 7 let map = {}; 8 for (let i = 0; i < s.length; i++) { 9 if (!map[s[i]]) { 10 map[s[i]] = 1; 11 } else { 12 map[s[i]]++; 13 } 14 } 15 for (let i = 0; i < t.length; i++) { 16 if (!map[t[i]] || map[t[i]] < 0) { 17 return false; 18 } else { 19 map[t[i]]--; 20 } 21 } 22 for (let key in map) { 23 if (map[key] !== 0) { 24 return false; 25 } 26 } 27 return true; 28 };