題目

You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:

Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. Align the substitution table with the regular English alphabet. Each letter in message is then substituted using the table. Spaces ’ ’ are transformed to themselves. For example, given key = “happy boy” (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of (‘h’ -> ‘a’, ‘a’ -> ‘b’, ‘p’ -> ‘c’, ‘y’ -> ’d’, ‘b’ -> ’e’, ‘o’ -> ‘f’). Return the decoded message.

Example 1

Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
Output: "this is a secret"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "the quick brown fox jumps over the lazy dog".
  • 題意: 將key中的字串透過abcdef…對應,之後透過message解法成正確的意思

解法

import (
	"strings"
)

var alpha = [26]string{
	"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
	"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
	"w", "x", "y", "z",
}

func decodeMessage(key string, message string) string {
    m := map[int32]string{}
	index := 0
	for _, v := range key {
		_, isExist := m[v]
		if v != 32 && !isExist {
			m[v] = alpha[index]
			index++
		}
	}
	res := strings.Builder{}
	for _, v := range message {
		if v == 32 {
			res.WriteString(" ")
		} else {
			res.WriteString(m[v])
		}
	}
	return res.String()
}
  • 寫個測試證明結果是否如預期
func Test_decodeMessage(t *testing.T) {
	res := decodeMessage("the quick brown fox jumps over the lazy dog", "vkbs bs t suepuv")
	fmt.Println(res)
	assert.Equal(t, "this is a secret", res)
}

參考連結