LeetCode One Question of the Day (61) 49. Grouping of Alphabetic Words (Hash+emplace_back)

49. Grouping of Letter Alien Words


Insert picture description here


class Solution {
    
    
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
    
    
        map<string,int> position; //纪录同一类别的位置
        vector<vector<string>> result; //结果
        int len=0;

        for(int i=0;i<strs.size();i++){
    
    
            string temp=strs[i];
            sort(temp.begin(),temp.end());
            //判断position里面是否有位置信息,没有就需要新增一个[]
            if(position.count(temp)==0){
    
     
                vector<string> x;
                result.push_back(x);
                position[temp]=len;
                len++;
            }
            result[position[temp]].push_back(strs[i]);
        }
        return result;
    }
};

Insert picture description here


In C++ development, we will often use insert operations to operate various stl containers, such as vector, map, set, etc. Before the introduction of rvalue references, transfer constructors, transfer copy operators, usually use push_back () to add an rvalue element (temporary object) to the container, first call the constructor to construct the temporary object, and then need to call the copy construction The function puts this temporary object in the container. The original temporary variables are released. The problem caused by this is the waste of temporary variable application resources.
Introduced rvalue references, after the transfer constructor, the constructor and transfer constructor will be called when push_back() rvalues. If it can be constructed directly when inserting, it only needs to be constructed once. This is what c++11 added emplace_back.

class Solution {
    
    
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
    
    
        unordered_map<string, vector<string>> mp;
        for (string& str: strs) {
    
    
            string key = str;
            sort(key.begin(), key.end());
            mp[key].emplace_back(str);
        }
        vector<vector<string>> ans;
        for (auto it = mp.begin(); it != mp.end(); ++it) {
    
    
            ans.emplace_back(it->second);
        }
        return ans;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45021180/article/details/111159580