๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Group Anagrams

by dkswnkk 2021. 11. 14.

๋ฌธ์ œ

 

Group Anagrams - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฝ”๋“œ

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {

        map<string,vector<string>>m;
        map<char,int>char_check;

        sort(strs.begin(),strs.end());

        vector<string>temp = strs;

        for(int i=0; i<temp.size(); i++){
            sort(temp[i].begin(),temp[i].end());
            m[temp[i]]={};
        }
        vector<string> origin = strs;

        for(int i=0; i<strs.size(); i++){
            sort(strs[i].begin(),strs[i].end());
            m[strs[i]].push_back(origin[i]);
        }

        vector<vector<string>>ans;

        for(auto i = m.begin(); i!=m.end(); i++){
            ans.push_back(i->second);
        }

      return ans;
    }
};

 

ํ’€์ด

์ž…๋ ฅ ๋ฐฐ์—ด ์•ˆ์˜ ๋ชจ๋“  ๋ฌธ์ž ๋ฐฐ์—ด ์†์˜ ๋ฌธ์ž์—ด๋“ค์„ ์ •๋ ฌํ•˜์—ฌ ๋งต ํ…Œ์ด๋ธ”์— ๋„ฃ์Šต๋‹ˆ๋‹ค. ๊ทธ ํ›„ strs ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋งŒํผ ๋Œ๋ฉด์„œ ์ •๋ ฌ ํ•œ ๋ฌธ์ž์˜ ๊ฐ’์ด ์žˆ๋Š” ๊ฒฝ์šฐ ์›๋ž˜ ์ •๋ ฌํ•˜๊ธฐ ์ „ ๋ฌธ์ž๋ฅผ ์‚ฝ์ž…ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ ํ›„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

๋ง์žฌ๊ฐ„์ด ์—†์–ด์„œ ์˜ˆ๋ฅผ ๋“ค์–ด ์„ค๋ช…ํ•˜์ž๋ฉด 

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

์œ„ ์™€ ๊ฐ™์€ ์ž…๋ ฅ์ด ์ฃผ์–ด์กŒ์„๋•Œ ๋จผ์ € 

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

์œ„์™€ ๊ฐ™์ด ์ •๋ ฌ์„ ์‹œ์ผœ์ค๋‹ˆ๋‹ค. ๊ทธ ํ›„  ๊ฐ ๋ฌธ์ž์—ด๋“ค์„ ์ •๋ ฌ ํ›„  ๋งต ํ…Œ์ด๋ธ”์— ๊ฐ’๋“ค์„ ์‚ฝ์ž…ํ•˜๋ฉด 

m["aet"]={}, m["abt"] = {}, m= ["ant"] = {}, 

์œ„์™€ ๊ฐ™์ด ๋งต ํ…Œ์ด๋ธ”์— ๊ฐ’๋“ค์ด ๋“ค์–ด๊ฐˆ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๊ทธ ํ›„ 

        for(int i=0; i<strs.size(); i++){
            sort(strs[i].begin(),strs[i].end());
            m[strs[i]].push_back(origin[i]);
        }

์œ„ ๊ณผ์ •์„ ๊ฑฐ์น˜๋ฉด m["aet"] ={"ate", "eat", "tea"}, m["abt"] ={"bat"}, m["ant"] = {"nat", "tan"} ์˜ ๊ฐ’์ด ๋ฉ๋‹ˆ๋‹ค.

์ด์ œ 2์ฐจ์› ๋ฒกํ„ฐ์— ์œ„ ๋งตํ…Œ์ด๋ธ”์˜ value ๊ฐ’๋“ค์„ ๋„ฃ์–ด์ฃผ๊ณ  ์ถœ๋ ฅํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

๋Œ“๊ธ€