zoukankan      html  css  js  c++  java
  • leetcode Group Anagrams

    题目连接

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

    Group Anagrams

    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”] 

    Note: 
    For the return value, each inner list’s elements must follow the lexicographic order. 
    All inputs will be in lower-case. 

    以一种奇怪的方式水过去了... __(:з」∠)__

    class Solution {
    public:
    	vector<vector<string>> groupAnagrams(vector<string>& strs) {
    		if (!strs.size()) return ans;
    		int n = strs.size();
    		vector<string> *ret = new vector<string>[n];
    		for (int i = 0; i < n; i++) {
    			string x = strs[i];
    			sort(x.begin(), x.end());
    			if (vis.find(x) == vis.end()) { 
    				vis[x] = i, index.insert(i);
    				ret[i].push_back(strs[i]);
    			} else { 
    				int v = vis[x];
    				vis[strs[i]] = v; 
    				ret[v].push_back(strs[i]);
    			}
    		}
    		for (set<int>::iterator i = index.begin(); i != index.end(); ++i) {
    			sort(ret[*i].begin(), ret[*i].end());
    			ans.push_back(ret[*i]);
    		}
    		sort(ans.begin(), ans.end(), cmp());
    		delete []ret;
    		return ans;
    	}
    private:
    	struct cmp {
    		bool operator()(const vector<string> &A, const vector<string> &B) {
    			int m = (int)A.size(), n = (int)B.size();
    			return n == m ? A[0] > B[0] : (bool)(n > m);
    		}
    	};
    	set<int> index;
    	unordered_map<string, int> vis;
    	vector<vector<string>> ans;
    };
  • 相关阅读:
    微信公众号菜单demo
    Hosts 广告
    thinkphp用swiftmailer发邮件demo
    微信小程序小结(4) -- 分包加载及小程序间跳转
    微信小程序小结(5) -- 常用语法
    常用SQL语句及在node中使用MySQL
    JavaScript -- tips
    CSS3 -- FlexBox(弹性盒子)
    gulp使用文档
    yarn快速使用及实践建议
  • 原文地址:https://www.cnblogs.com/GadyPu/p/5040135.html
Copyright © 2011-2022 走看看