//第一种map方法
function groupAnagrams(strs) {let map = new Map()for (let str of strs) {let key = str === '' ? ' ' : str.split('').sort().join('')if (!map.has(key)) {map.set(key, [])}map.get(key).push(str)}
//此时map为Map(3) {'aet' => [ 'eat', 'tea', 'ate' ],'ant' => [ 'tan', 'nat' ],'abt' => [ 'bat' ]
}return Array.from(map.values())
}
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
//[ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ]//第二种方法
function second(strs){let flag_array = []let array = []for (let i = 0; i < strs.length; i++) {if(strs[i].length>0){let temp = ''temp = strs[i].split('').sort().join('')if(flag_array.indexOf(temp)== -1){flag_array.push(temp)array.push([strs[i]])}else{array[flag_array.indexOf(temp)].push(strs[i])}}else{let emptyIndex = flag_array.indexOf('') if(emptyIndex === -1){flag_array.push('')array.push([""]) } else {array[emptyIndex].push("") }}}return array
}
const array = s.split(" ");if (array.length !== pattern.length) {return false;}const charmap = new Map()const strmap = new Map()for (let i = 0; i < array.length; i++) {const char = array[i]const str = pattern[i]if (charmap.has(char)) {if (charmap.get(char) != str) {return false}}else {charmap.set(char, str)}if (strmap.has(str)) {if (strmap.get(str) != char) {return false}} else {strmap.set(str, char)}}return true
附带字符串小知识点:
字符串按字母顺序排列:str.split('').sort().join('')
Math.min()
方法不接受数组作为参数,需要如下写法
Math.min(...[0, 1, 2]);