题解 | #字符串加密#

字符串加密

https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3

package main

import (
    "fmt"
    "os"
    "bufio"
)

func encrypt(key string, word string) string {
    letterTable := "abcdefghijklmnopqrstuvwxyz"

    m := make(map[byte]struct{})
    var keyPrefix []byte
    for i:=0; i<len(key); i++ {
        if _, ok := m[key[i]]; !ok {
            keyPrefix = append(keyPrefix, key[i])
            m[key[i]] = struct{}{}
        }
    }

    for i:=0; i<len(letterTable); i++ {
        if _, ok := m[letterTable[i]]; !ok {
            keyPrefix = append(keyPrefix, letterTable[i])
            m[letterTable[i]] = struct{}{}
        }
    }

    sb := []byte(word)
    for i:=0; i<len(sb); i++ {
        if 'a' <= sb[i] && sb[i] <= 'z' {
            sb[i] = keyPrefix[sb[i]-'a']
        }
    }

    return string(sb)
}

func main() {
    var key string
    var word string

    inputReader := bufio.NewReader(os.Stdin)
    line, _, _ := inputReader.ReadLine()
    key = string(line)

    line, _, _ = inputReader.ReadLine()
    word = string(line)

    fmt.Println(encrypt(key, word))
}
// 输入为两行字符串,可能包含空格,所以采用:inputReader.ReadLine()

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务