> For the complete documentation index, see [llms.txt](https://frost.gitbook.io/iosbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://frost.gitbook.io/iosbook/leet-code/leetcode-solutions/49.-group-anagrams.md).

# \[LeetCode] 49. Group Anagrams

Given an array of strings, group anagrams together.

**Example:**

```
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
```

**Note:**

* All inputs will be in lowercase.
* The order of your output does not matter.

**Analyse:**

​

**Solution:**

```swift
class Solution {

    func groupAnagrams(_ strs: [String]) -> [[String]] {
        var copyStr = strs;
        var output:[[String]]  = [];
        var sortedStrs:[String:[String]] = [:];
        
        var i = 0;
        while(i < copyStr.count) {
            var str = copyStr[i];
            str = String(str.sorted{$0 < $1})
            
            if(sortedStrs[str] != nil) {
                var strs: [String] = sortedStrs[str]!;
                strs.append(copyStr[i]);
                sortedStrs[str] = strs;
            }
            else {
                sortedStrs[str] = [copyStr[i]]; 
            }
                
            i += 1;
        }

        for xxx in sortedStrs {
            output.append(xxx.value);
        }
        
        return output;
    } 
}
```
