# 49. Group Anagrams

## 1.問題

* **給予一個string 的array, 將相同anagrams的字串分組**

![](/files/-LNtrBkCJ-1z9nuyQWbB)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
* function header, parameter
* test input
* 說明想法
  * 可以把這題視為分組問題, 因此分組的關鍵在於將相同key的放在一起, 如果對容器的使用足夠熟悉, 會想到用map搭配vector存放同一群組的string
  * key可以是經過sort的string, 或是另一個map
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        
        if (strs.empty()) {
            return res;
        }    
        
        map<string, vector<string>> m1;
        
        for (int i = 0; i < strs.size(); i++) {
            string key = strs[i];
            sort(key.begin(), key.end());
            m1[key].push_back(strs[i]);
        }
        
        for (map<string, vector<string>>::iterator it= m1.begin(); it != m1.end(); it++) {
            res.push_back(it->second);
        }
        return res;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/49.-group-anagrams.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
