-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmorse_code.go
45 lines (40 loc) · 1.27 KB
/
morse_code.go
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
package morse_code
import "strings"
// Encode 对输入的内容进行摩斯密码编码
func Encode(plaintext string) ([]string, error) {
plaintextRuneSlice := []rune(plaintext)
result := make([]string, len(plaintextRuneSlice))
for index, character := range plaintextRuneSlice {
if to, exists := DefaultMorseCodeTable[character]; exists {
result[index] = to
} else {
return nil, ErrNotSupportMorseCharacter
}
}
return result, nil
}
// EncodeToString 编码为摩尔斯密码的字符串
func EncodeToString(plaintext string) (string, error) {
encode, err := Encode(plaintext)
if err != nil {
return "", err
}
return strings.Join(encode, " "), nil
}
// Decode 对输入的内容进行摩斯密码解码,多个摩尔斯密码之间使用空格分割
func Decode(ciphertext string) (string, error) {
split := strings.Split(ciphertext, " ")
return DecodeMorseCodeSlice(split)
}
// DecodeMorseCodeSlice 解码摩尔斯密码数组
func DecodeMorseCodeSlice(morseCodeSlice []string) (string, error) {
resultSlice := make([]rune, len(morseCodeSlice))
for index, morseCode := range morseCodeSlice {
character, err := DefaultMorseSearchTree.Query(morseCode)
if err != nil {
return "", err
}
resultSlice[index] = character
}
return string(resultSlice), nil
}