-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathlzw.go
More file actions
134 lines (108 loc) · 2.36 KB
/
lzw.go
File metadata and controls
134 lines (108 loc) · 2.36 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*
*
* LZW压缩算法 - 字典压缩
*
* 问题:使用动态字典进行无损数据压缩
*
* 核心思想:
* - 动态构建编码字典
* - 查找最长匹配字符串
* - 输出字典索引
*
* 时间复杂度: O(n)
* 空间复杂度: O(n)
*/
package main
import (
"fmt"
"strconv"
)
const maxDictSize = 4096
/*
*
* LZW压缩
*/
func lzwCompress(input string) []int {
dictionary := make(map[string]int)
// 初始化字典(单字符)
for i := 0; i < 256; i++ {
dictionary[string(rune(i))] = i
}
compressed := []int{}
current := ""
dictSize := 256
for _, char := range input {
combined := current + string(char)
if _, exists := dictionary[combined]; exists {
current = combined
} else {
// 输出current的编码
compressed = append(compressed, dictionary[current])
// 将combined加入字典
if dictSize < maxDictSize {
dictionary[combined] = dictSize
dictSize++
}
// 重置current为char
current = string(char)
}
}
// 输出最后一个编码
if current != "" {
compressed = append(compressed, dictionary[current])
}
return compressed
}
/*
*
* LZW解压
*/
func lzwDecompress(compressed []int) string {
dictionary := make(map[int]string)
// 初始化字典(单字符)
for i := 0; i < 256; i++ {
dictionary[i] = string(rune(i))
}
output := ""
oldCode := compressed[0]
oldString := dictionary[oldCode]
output += oldString
dictSize := 256
for i := 1; i < len(compressed); i++ {
newCode := compressed[i]
var stringVal string
if _, exists := dictionary[newCode]; !exists {
// 特殊情况:new_code不在字典中
stringVal = oldString + string(oldString[0])
} else {
stringVal = dictionary[newCode]
}
output += stringVal
// 将old_string + string[0]加入字典
if dictSize < maxDictSize {
dictionary[dictSize] = oldString + string(stringVal[0])
dictSize++
}
oldString = stringVal
}
return output
}
/*
*
* 主函数
*/
func main() {
input := "TOBEORNOTTOBEORTOBEORNOT"
fmt.Println("=== LZW压缩算法 ===")
fmt.Println("原始文本:", input)
compressed := lzwCompress(input)
fmt.Print("压缩后编码: ")
for _, code := range compressed {
fmt.Print(strconv.Itoa(code) + " ")
}
fmt.Println()
decompressed := lzwDecompress(compressed)
fmt.Println("解压后文本:", decompressed)
valid := input == decompressed
fmt.Println("验证:", valid)
}