table of Contents
# Front end of the algorithm leetcode 242. effective letter word ectopic
Title Description
Given two strings s and t, t write a function to determine whether the ectopic letters of the word s.
Example 1:
输入: s = "anagram", t = "nagaram"
输出: true
Example 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
Advanced:
If the input string contains unicode characters how to do? Can you adjust your solution to deal with this situation?
242. Effective ectopic letter word
Overview
Analyzing the word ectopic many ways, can be a hash table may be constructed determined character array 26, may also be determined whether the sorted strings are equal according to the number of times each character appears
prompt
Hash, Array
Resolve
Solution one: hash table
Hash table In this problem in general, but when you see this problem is often the first time will be able to think of this approach. Then build a HashMap s count the number of each word appears, then use this table to judge all the characters in the first t the number of occurrences, once the number of characters that appear are not equal or do not have this character returns false
Solution two: an array of characters to determine the number of occurrences
Constructed an array of length 26 is then completely filled 0, then s the s[i]
characters appear number in the index position once self-imposed time, t[i]
the corresponding index is decremented once, the final outcome has a non-zero indicates s and t are not equal
Solution three: convert a string
Reconciliation two ideas are similar, but in fact, after sorting determine whether the strings are equal
algorithm
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
// 哈希法
// if (s.length !== t.length) {return false;}
// let map = new Map();
// for (let i = 0;i < s.length;i++) {
// map.get(s[i]) === undefined ? map.set(s[i], 1) : map.set(s[i], map.get(s[i]) + 1);
// }
// for (let j = 0;j < t.length;j++) {
// if (map.get(t[j]) > 0) {map.set(t[j], (map.get(t[j])) - 1);} else {return false;}
// }
// return true;
// 26个字符法
if (s.length !== t.length) {return false;}
let kmap = new Array(26).fill(0);
for (let i = 0 ;i < s.length;i++) {
kmap[s[i].charCodeAt(0) - 97]++;
kmap[t[i].charCodeAt(0) - 97]--;
}
for (let i = 0;i < 26;i++) {
if (kmap[i] !== 0) {return false;}
}
return true;
// 解法三
// if (s.length !== t.length) return false
// let o = new Array(26).fill(0)
// for (let i = 0; i < s.length; i++) {
// o[s[i].charCodeAt(0) - 97]++
// }
// let p = new Array(26).fill(0)
// for (let i = 0; i < t.length; i++) {
// p[t[i].charCodeAt(0) - 97]++
// }
// o = o.toString()
// p = p.toString()
// return o === p
};
Incoming operating results of test cases
input:"rat","art"
output:true
Results of the
执行用时 :68 ms, 在所有 javascript 提交中击败了98.28%的用户
内存消耗 :35.7 MB, 在所有 javascript 提交中击败了87.50%的用户