zoukankan      html  css  js  c++  java
  • [Leetcode] Group Anagrams

    Group Anagrams 题解

    原创文章,拒绝转载

    题目来源:https://leetcode.com/problems/group-anagrams/description/


    Description

    Given an array of strings, group anagrams together.

    For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],

    Return:

    
    [
      ["ate", "eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]
    
    

    Solution

    
    class Solution {
    private:
        struct cmp {
            bool operator() (char a, char b) {
                return a < b;
            }
        } cmpObj;
    public:
        vector<vector<string> > groupAnagrams(vector<string>& strArr) {
            size_t size = strArr.size();
            vector<vector<string> > res;
            if (size == 0)
                return res;
            unordered_map<string, vector<string>> hs;
            for (auto& str : strArr) {
                string key = str;
                sort(key.begin(), key.end(), cmpObj);
                hs[key].push_back(str);
            }
            for (auto& item: hs) {
                res.push_back(item.second);
            }
            return res;
        }
    };
    
    

    解题描述

    这道题题意是,给出一个字符串数组,将其中的字符串归类,归类的依据是每个同一类的字符串之间仅通过变换字符位置就可以互相转换。这样一个问题还是属于哈希的问题,我使用了底层实现为哈希表的STL容器unordered_map来存储哈希项,对插入哈希表的字符串,计算哈希值的时候只需要对字符串排序。

  • 相关阅读:
    类加载,初始化
    jvm classLoader architecture
    只选择年份的下拉菜单
    spring框架学习(二)依赖注入
    spring框架学习(一)
    JSP 过滤器
    JSP9个内置对象
    JSP 动作元素
    众数
    基于excel9.h的excel处理
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8340449.html
Copyright © 2011-2022 走看看