-
Notifications
You must be signed in to change notification settings - Fork 41
/
49.swift
77 lines (65 loc) · 1.71 KB
/
49.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// 49.swift
// LeetCode
//
// Created by Lex on 12/22/15.
// Copyright © 2015 Lex Tang. All rights reserved.
//
/*
Group Anagrams
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:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
*/
import Foundation
import XCTest
func groupAnagrams(_ a: [String]) -> [[String]] {
var array = a.reversed() as [String]
var group = [[String]]()
while true {
guard let last = array.popLast() else {
break
}
group.append([last])
var i = array.count
while i > 0 {
i -= 1
if isAnagram(array[i], last) {
if var lastGroup = group.popLast() {
lastGroup.append(array[i])
lastGroup = lastGroup.sorted()
group.append(lastGroup)
array.remove(at: i)
}
}
}
}
return group
}
class GroupAnagramsTest: XCTestCase {
func testGroupAnagrams() {
let group = groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
XCTAssertEqual(group.first!, ["ate", "eat", "tea"])
// XCTAssertEqual(group,
// [
// ["ate", "eat", "tea"],
// ["nat", "tan"],
// ["bat"]
// ]
// )
//
// group = groupAnagrams(["a", "b", "c"])
// XCTAssertEqual(group, [["a"], ["b"], ["c"]])
//
// group = groupAnagrams(["", "cb", "bc"])
// XCTAssertEqual(group, [[""], ["bc", "cb"]])
}
}