zoukankan      html  css  js  c++  java
  • Group Anagrams

    Total Accepted: 57578 Total Submissions: 226493 Difficulty: Medium

    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.
     
    先对每个字符串排序,生成新的串,再对新的串排序,排序好的字符串就是按anagrams规则放在一起
    struct Node{
        string origin;
        string str;
        Node(string& originValue,string& strValue):origin(originValue),str(strValue){}
    };
    int CompStr(const string& lhs,const string& rhs)
    {
        int i=0;
        while(i<lhs.size() && i<rhs.size()){
            if(lhs[i] < rhs[i]){
                return 1;
            }else if(lhs[i] > rhs[i]){
                return -1;
            }
            i++;
        }
        if(i==lhs.size() && i==rhs.size()){
            return 0;
        }
        return i<rhs.size() ? 1:-1;
    }
    bool CompNode(const Node& lhs,const Node& rhs){
        int res = CompStr(lhs.str,rhs.str);
        if(res == 0){
            res = CompStr(lhs.origin,rhs.origin);
        }
        return res==1 ? true:false;
    }
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            int strsSize = strs.size();
            vector<Node> nodes;
            for(int i=0;i<strsSize;i++){
                string str = strs[i];
                sort(str.begin(),str.end());
                nodes.push_back(Node(strs[i],str));
            }
            sort(nodes.begin() ,nodes.end(),CompNode);
            vector<vector<string>> res;
            vector<string> group;
            for(int i=0;i<strsSize;i++){
                if(i>0 && nodes[i].str!=nodes[i-1].str){
                    res.push_back(group);
                    group.clear();
                }
                group.push_back(nodes[i].origin);
            }
            res.push_back(group);
            return res;
        }
    };
  • 相关阅读:
    【Eclipse导入外部包解决方案】由GoogleMap导入gms包问题引出
    新生活即将开始

    继续我的C旅程
    圣诞后
    新年
    来来回回;不知所云
    吵啊吵啊吵啊
    去海边
    休假结束
  • 原文地址:https://www.cnblogs.com/zengzy/p/5036982.html
Copyright © 2011-2022 走看看