zoukankan      html  css  js  c++  java
  • LeetCode.49

      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: All inputs will be in lower-case.

      这个题没太懂该怎么输出,它给的返回类型是多维数组...看讨论貌似只需要把与自己排序字符串相同的放在一起就可以了。

      于是,我的代码:

    class Solution {
    public:
        vector<string> groupAnagrams(vector<string>& strs) {
            vector<int> sum;
            string arr;
    
            for(int i = 0; i < (int)strs.size(); i++) {     //  O(n*m)
                sum.push_back(0);
                arr = strs[i];
                for(int j = 0; arr[j] != ''; j++)
                    sum[i] += (int)arr[j];
            }
    
            vector<string> mapstrs;
            int len = (int)strs.size();
            for(int i = 0; i < len;) {  //  O(n)
                int temp = sum[i];
                for(int j = 0; j < len; j++)
                    if(temp == sum[j]) {
                        mapstrs.push_back(strs[j]);
                        int k = j;
                        while(k + 1 < len) {
                            strs[k] = strs[k + 1];
                            sum[k] = sum[k + 1];
                            k++;
                        }
                        len = k;
                    }
            }
            return mapstrs;
        }
    };

      时间复杂度为O(n*m),其中n为字符串个数,m为最长字符串中字符的个数。

      但它给的例子是这样的:

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

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

      所以,完全错误,并没有AC。这里考点是hash。。。所以,没必要这么麻烦。
      
      讨论区看到一个python的solution,感觉不错:
    # https://leetcode.com/problems/group-anagrams/discuss/19202
    class Solution:
    	def groupAnagrams(self, strs):
    		d = {}
    		for w in sorted(strs):
    			key = tuple(sorted(w))
    			d[key] = d.get(key, []) + [w]
    		return d.values()
    
    strs = ['dog','cat','god','tac','atc','oob']
    so = Solution()
    print(so.groupAnagrams(strs))
  • 相关阅读:
    左偏树
    论在Windows下远程连接Ubuntu
    ZOJ 3711 Give Me Your Hand
    SGU 495. Kids and Prizes
    POJ 2151 Check the difficulty of problems
    CodeForces 148D. Bag of mice
    HDU 3631 Shortest Path
    HDU 1869 六度分离
    HDU 2544 最短路
    HDU 3584 Cube
  • 原文地址:https://www.cnblogs.com/darkchii/p/8279839.html
Copyright © 2011-2022 走看看