Code Monkey home page Code Monkey logo

Comments (2)

bazinga-web avatar bazinga-web commented on June 21, 2024

解题思路:

  1. 如果为空数组直接返回空数组
  2. 遍历单词数组,为每个单词建立长度为26的内容为0的数组,同时遍历每个单词将
    每个字母出现的频率记录到数组指定位置(利用ASCII码)
  3. 将同等频率的单词放入Hash Map中
  4. 遍历map,将结果返回
/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function (strs) {
  let result = [];
  if (strs.length === 0) return result;
  let map = new Map();
  for (const str of strs) {
    let arr = new Array(26).fill(0);
    for (let i = 0; i < str.length; i++) {
      const ascii = str[i].charCodeAt() - 97;
      arr[ascii]++;
    }
    const key = arr.join("");
    if (map.has(key)) {
      map.set(key, [...map.get(key), str]);
    } else {
      map.set(key, [str]);
    }
  }
  for (const value of map.values()) {
    result.push(value);
  }
  return result;
};

from like-algorithms.

Ray-56 avatar Ray-56 commented on June 21, 2024

哈希表解

复杂度O(NKlogK), N 为 strs 长度,K 为 strs 中每个字符串的长度

const len = strs.length;
	if (!len) return [];
	const ret = [];
	const map = new Map();
	for (let i = 0; i < len; i++) {
		let newStr = strs[i].split('').sort().join(''); // 拆分排序合并后作为 key
		if (map.has(newStr)) {
			const old = map.get(newStr);
			old.push(strs[i]);
			map.set(newStr, old);
		} else {
			map.set(newStr, [strs[i]]);
		}
	}

	return Array.from(map.values());

from like-algorithms.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.