【算法】2325. 解密消息(多语言实现)

71 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第18天,点击查看活动详情


2325. 解密消息:

给你字符串 keymessage ,分别表示一个加密密钥和一段加密消息。解密 message 的步骤如下:

  1. 使用 key 中 26 个英文小写字母第一次出现的顺序作为替换表中的字母 顺序
  2. 将替换表与普通英文字母表对齐,形成对照表。
  3. 按照对照表 替换 message 中的每个字母。
  4. 空格 ' ' 保持不变。
  • 例如,key = "happy boy"(实际的加密密钥会包含字母表中每个字母 至少一次),据此,可以得到部分对照表('h' -> 'a''a' -> 'b''p' -> 'c''y' -> 'd''b' -> 'e''o' -> 'f')。

返回解密后的消息。

样例 1:

输入:
	key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
	
输出:
	"this is a secret"
	
解释:
	对照表如上图所示。
	提取 "the quick brown fox jumps over the lazy dog" 中每个字母的首次出现可以得到替换表。

样例 2:

输入:
	key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
	
输出:
	"the five boxing wizards jump quickly"
	
解释:
	对照表如上图所示。
	提取 "eljuxhpwnyrdgtqkviszcfmabo" 中每个字母的首次出现可以得到替换表。

提示:

  • 26 <= key.length <= 2000
  • key 由小写英文字母及 ' ' 组成
  • key 包含英文字母表中每个字符('a''z')至少一次
  • 1 <= message.length <= 2000
  • message 由小写英文字母和 ' ' 组成

分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 根据题意,分两步做即可。
  • 第一步:生成加密对照表,可以使用map,set等数据结构,数组也是可以的。
  • 第二步:利用对照表解密消息,字符串如果是不可变的,那只能开辟新的空间,否则也可以原地修改。

题解

rust

impl Solution {
    pub fn decode_message(key: String, mut message: String) -> String {
        // 生成映射表
        let mut tab = vec![0u8; 26];
        let mut k = 97u8;
        key.as_bytes().iter().for_each(|&b| {
            if b != ' ' as u8 && tab[(b - 97) as usize] == 0 {
                tab[(b - 97) as usize] = k;
                k += 1;
            }
        });

        // 解密
        unsafe {
            message.as_bytes_mut().iter_mut().for_each(|b| {
                if *b != ' ' as u8 {
                    *b = tab[(*b - 97) as usize];
                }
            });
        }

        message
    }
}

go

func decodeMessage(key string, message string) string {
    // 生成对照表
    tab := [26]byte{}
    k := byte('a')
    for _, b := range key {
        if b != ' ' && tab[b-'a'] == 0 {
            tab[b-'a'] = k
            k++
        }
    }

    // 解密消息
    bs := []byte(message)
    for i, b := range bs {
        if b != ' ' {
            bs[i] = tab[b-'a']
        }
    }

    return string(bs)
}

typescript

function decodeMessage(key: string, message: string): string {
    // 生成对照表
    const tab = { ' ': ' ' };
    let k = 97;
    for (const c of key) {
        if (!tab[c]) {
            tab[c] = String.fromCharCode(k);
            ++k;
        }
    }

    // 解密消息
    return message.split('').map(c => tab[c]).join('');
};

python

class Solution:
    def decodeMessage(self, key: str, message: str) -> str:
        # 生成对照表
        tab = {' ': ' '}
        i = 0
        for c in key:
            if c not in tab:
                tab[c] = ascii_lowercase[i]
                i += 1
        # 解密消息
        return ''.join(tab[c] for c in message)


c

char * decodeMessage(char * key, char * message){
    // 生成对照表
    char tab[26] = {};
    char k = 'a';
    while (*key) {
        if (*key != ' ' && tab[(*key) - 'a'] == 0) {
            tab[(*key) - 'a'] = k++;
        }
        ++key;
    }

    // 解密消息
    char *t = message;
    while (*t) {
        if (*t != ' ') {
            *t = tab[(*t) - 'a'];
        }
        ++t;
    }
    return message;
}

c++

class Solution {
public:
    string decodeMessage(string key, string message) {
        // 生成对照表
        char tab[26] = {};
        char k = 'a';
        for (auto c: key) {
            if (c != ' ' && tab[c - 'a'] == 0) {
                tab[c - 'a'] = k++;
            }
        }

        // 解密消息
        for (int i = 0; i < message.length(); ++i) {
            if (message[i] != ' ') {
                message[i] = tab[message[i] - 'a'];
            }
        }
        return message;
    }
};

java

class Solution {
    public String decodeMessage(String key, String message) {
        // 生成对照表
        char[] tab = new char[26];
        char k = 'a';
        for (char c : key.toCharArray()) {
            if (c != ' '
                    && tab[c - 'a'] == 0) {
                tab[c - 'a'] = k++;
            }
        }

        // 解密消息
        char[] cs = message.toCharArray();
        for (int i = 0; i < cs.length; ++i) {
            char c = cs[i];
            if (c != ' ') {
                cs[i] = tab[c - 'a'];
            }
        }

        return String.valueOf(cs);
    }
}

原题传送门:https://leetcode.cn/problems/decode-the-message/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~