forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GeneralizedAbbreviation.swift
36 lines (30 loc) · 1007 Bytes
/
GeneralizedAbbreviation.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
/**
* Question Link: https://leetcode.com/problems/generalized-abbreviation/
* Primary idea: Classic Depth-first Search
*
* Time Complexity: O(n^n), Space Complexity: O(2^n)
*
*/
class GeneralizedAbbreviation {
func generateAbbreviations(_ word: String) -> [String] {
var res = [String]()
let chars = Array(word.characters)
dfs(chars, &res, "", 0)
return res
}
private func dfs(_ word: [Character], _ res: inout [String], _ subset: String, _ index: Int) {
if word.count == index {
res.append(String(subset))
return
}
res.append(subset + String(word.count - index))
for i in index..<word.count {
let offset = i - index
if offset != 0 {
dfs(word, &res, subset + String(offset) + String(word[i]), i + 1)
} else {
dfs(word, &res, subset + String(word[i]), i + 1)
}
}
}
}