Skip to content

Commit 7cf2e95

Browse files
committed
0320. 列举单词的全部缩写
1 parent 9d96048 commit 7cf2e95

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package leetcode_0320_generalized_abbreviation
2+
3+
import "strconv"
4+
5+
// 0320. 列举单词的全部缩写
6+
// https://leetcode.cn/problems/generalized-abbreviation/
7+
8+
// generateAbbreviations dfs
9+
// 时间复杂度: O(n*2^n)
10+
// 空间复杂度: O(n)
11+
func generateAbbreviations(word string) []string {
12+
var (
13+
n = len(word)
14+
// i为当前遍历到字符串的第几个字符
15+
// k为连续缩写的字符个数
16+
dfs func(i, k int, path string)
17+
ans []string
18+
)
19+
20+
dfs = func(i, k int, path string) {
21+
if i == n {
22+
if k > 0 {
23+
// 若计数大于0,则转为字符串,加到末尾
24+
path += strconv.Itoa(k)
25+
}
26+
ans = append(ans, path)
27+
return
28+
}
29+
30+
// a.每个字符有两种选择,一种是缩写
31+
dfs(i+1, k+1, path)
32+
// b.一种是不缩写。不缩写的时候,要把之前的k转换为string加到path后面,然后再添加字符本身
33+
if k > 0 {
34+
path += strconv.Itoa(k)
35+
}
36+
path += string(word[i])
37+
dfs(i+1, 0, path)
38+
}
39+
dfs(0, 0, "")
40+
return ans
41+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package leetcode_0320_generalized_abbreviation
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func Test_generateAbbreviations(t *testing.T) {
9+
word := "word"
10+
// [4 3d 2r1 2rd 1o2 1o1d 1or1 1ord w3 w2d w1r1 w1rd wo2 wo1d wor1 word]
11+
fmt.Println(generateAbbreviations(word))
12+
}

0 commit comments

Comments
 (0)