zoukankan      html  css  js  c++  java
  • 49. Group Anagrams (string, HashTable)

    Given an array of strings, group anagrams together.

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

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

    Note:

    1. For the return value, each inner list's elements must follow the lexicographic order.
    2. All inputs will be in lower-case.

    思路:

    anagram: 由颠倒字母而成的单词

    anagram是否出现过,可以通过Hashmap,但是由于anagram无关乎字母出现的顺序,所以也可以将字母排序后再比较字符串。

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            if (strs.size() <= 0) return result;
            
            vector<vector<string>> result;
            map<string,int> anagram;
            int resIndex = 0;
            string s;
            
            for (int i = 0; i < strs.size(); ++i)
            {
                s = strs[i];
                sort(s.begin(), s.end()); //anagram无关乎字母顺序,所以将string按字母排序后再比较
                if (anagram.find(s) == anagram.end()) { //如果还没有出现过该anagram
                    vector<string> item;
                    item.push_back(strs[i]);
                    result.push_back(item);
                    anagram.insert(make_pair(s, resIndex++));
                } else {
                    result[anagram[s]].push_back(strs[i]);
                }
            }
            
            //each inner list's elements must follow the lexicographic order
            for(int i = 0; i < result.size(); i++){
                sort(result[i].begin(), result[i].end());
            }
            return result;
        }
    };
  • 相关阅读:
    HTML5存储
    HTML5 地理位置定位(Geolocation)原理及应用
    HTML5多媒体组件的使用
    HTML5拖拽
    HTML5一些总结
    js高级程序设计--数据类型
    JS高级程序设计基本概念
    浏览器内核、渲染引擎、js引擎
    JS高级程序设计笔记之script标签
    CenOS7下安装 nginx
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854871.html
Copyright © 2011-2022 走看看