zoukankan      html  css  js  c++  java
  • leetcode@ [49] Group Anagrams (Hashtable)

    https://leetcode.com/problems/anagrams/

    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.
    class node {
        public:  
            int idx;
            string s;
            node(int i, string str) {
                idx =i;
                s = str;
            }
            bool operator < (const node& rhs) {
                if(s.compare(rhs.s) < 0 || (s.compare(rhs.s) == 0 && idx < rhs.idx))  return true;
                return false;
            }
    };
    
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string> > res;
            
            int n = strs.size();
            if(n == 0)  return res;
            if(n == 1) {
                vector<string> tmp;
                tmp.push_back(strs[0]);
                res.push_back(tmp);
                return res;
            }
            
            vector<vector<char> > vec(n);
            vector<node> cs;
            for(int i=0; i<n; ++i) {
                for(int j=0; j<strs[i].length(); ++j) {
                    vec[i].push_back(strs[i][j]);
                }
                sort(vec[i].begin(), vec[i].end());
                
                string ss = "";
                for(int k=0; k<vec[i].size(); ++k) {
                    ss += vec[i][k];
                }
                cs.push_back(node(i, ss));
            }
            sort(cs.begin(), cs.end());
            
            int l = 0, r = l+1;
            while(r < n) {
                while(r < n && (cs[l].s).compare(cs[r].s) == 0)  ++r;
                
                vector<string> row;
                for(int p=l; p<r; ++p)  row.push_back(strs[cs[p].idx]);
                res.push_back(row);
                
                l = r; r = l+1;
            }
            
            if(l < n) {
                vector<string> row;
                row.push_back(strs[cs[n-1].idx]);
                res.push_back(row);
            }
            for(int i=0; i<res.size(); ++i) {
                sort(res[i].begin(), res[i].end());
            }
            
            return res;
        }
    };
  • 相关阅读:
    C语言博客作业-字符数组
    C语言博客作业--一二维数组
    个人作业5
    个人作业4
    个人作业3
    201521123072 结对编程
    软件工程 个人阅读作业2
    软件工程 个人阅读作业
    java课程设计--WeTalk(201521123072秦贞一)
    201521123072《java程序设计》第十四周学习总结
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5202574.html
Copyright © 2011-2022 走看看