-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path320-GeneralizedAbbreviation.go
More file actions
66 lines (57 loc) · 2.31 KB
/
320-GeneralizedAbbreviation.go
File metadata and controls
66 lines (57 loc) · 2.31 KB
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
package main
// 320. Generalized Abbreviation
// A word's generalized abbreviation can be constructed by taking any number of non-overlapping and non-adjacent
// substrings and replacing them with their respective lengths.
// For example, "abcde" can be abbreviated into:
// "a3e" ("bcd" turned into "3")
// "1bcd1" ("a" and "e" both turned into "1")
// "5" ("abcde" turned into "5")
// "abcde" (no substrings replaced)
// However, these abbreviations are invalid:
// "23" ("ab" turned into "2" and "cde" turned into "3") is invalid as the substrings chosen are adjacent.
// "22de" ("ab" turned into "2" and "bc" turned into "2") is invalid as the substring chosen overlap.
// Given a string word, return a list of all the possible generalized abbreviations of word.
// Return the answer in any order.
// Example 1:
// Input: word = "word"
// Output: ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
// Example 2:
// Input: word = "a"
// Output: ["1","a"]
// Constraints:
// 1 <= word.length <= 15
// word consists of only lowercase English letters.
import "fmt"
import "strconv"
func generateAbbreviations(word string) []string {
n, res := len(word), []string{}
var dfs func(path []byte, p int, c bool)
dfs = func(path []byte, p int, c bool){
if p == n {
res = append(res, string(path))
return
}
if c { // 当前可以缩写
for i := 1; i <= n - p; i++ { // 分别缩写多个长度
dfs(append(path, []byte(strconv.Itoa(i))...), p + i, false)
}
} else { // 不可以缩写
for i := 1; i <= n - p; i++ { // 分别不缩写多个长度
dfs(append(path,word[p:p+i]...), p+i, true)
}
}
}
dfs([]byte{}, 0, true)
dfs([]byte{}, 0, false)
return res
}
func main() {
// Example 1:
// Input: word = "word"
// Output: ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
fmt.Println(generateAbbreviations("word")) // ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
// Example 2:
// Input: word = "a"
// Output: ["1","a"]
fmt.Println(generateAbbreviations("a")) // ["1","a"]
}