【算法】804. 唯一摩尔斯密码词(多语言实现)

118 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第8天,点击查看活动详情


804. 唯一摩尔斯密码词:

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如:

  • 'a' 对应 ".-"
  • 'b' 对应 "-..."
  • 'c' 对应 "-.-." ,以此类推。

为了方便,所有 26 个英文字母的摩尔斯密码表如下:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

给你一个字符串数组 words ,每个单词可以写成每个字母对应摩尔斯密码的组合。

  • 例如,"cab" 可以写成 "-.-..--..." ,(即 "-.-." + ".-" + "-..." 字符串的结合)。我们将这样一个连接过程称作 单词翻译

words 中所有单词进行单词翻译,返回不同 单词翻译 的数量。

样例 1:

输入: 
	words = ["gin", "zen", "gig", "msg"]
	
输出: 
	2
	
解释: 
	各单词翻译如下:
	"gin" -> "--...-."
	"zen" -> "--...-."
	"gig" -> "--...--."
	"msg" -> "--...--."
	
	共有 2 种不同翻译, "--...-.""--...--.".

样例 2:

输入:
	words = ["a"]
	
输出:
	1

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 12
  • words[i] 由小写英文字母组成

分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 将所有单词翻译成摩尔斯密码,看一共翻译出几种就是答案。

题解

java

class Solution {
    private static final String[] MORSE = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
	
    public int uniqueMorseRepresentations(String[] words) {
        Set<String> seen = new HashSet<>();

        StringBuilder code = new StringBuilder();
        for (String word : words) {
            code.setLength(0);
            for (char c : word.toCharArray()) {
                code.append(MORSE[c - 'a']);
            }
            seen.add(code.toString());
        }

        return seen.size();
    }
}

c

#define MAX_STR_LEN 64

typedef struct {
    char key[MAX_STR_LEN];
    UT_hash_handle hh;
} HashItem;

const static char * MORSE[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};

int uniqueMorseRepresentations(char ** words, int wordsSize){
    HashItem * seen = NULL;
    for (int i = 0; i < wordsSize; i++) {
        HashItem * pEntry = NULL;
        int len = strlen(words[i]);
        int pos = 0;
        char code[MAX_STR_LEN];
        for (int j = 0; j < len; j++) {
            pos += sprintf(code + pos, "%s", MORSE[words[i][j] - 'a']);
        }
        HASH_FIND_STR(seen, code, pEntry);
        if (NULL == pEntry) {
            pEntry = (HashItem *)malloc(sizeof(HashItem));
            strcpy(pEntry->key, code);
            HASH_ADD_STR(seen, key, pEntry);
        }
    }
    int ans = HASH_COUNT(seen);
    HashItem * curr = NULL, * tmp = NULL;
    HASH_ITER(hh, seen, curr, tmp) {
        HASH_DEL(seen, curr); 
        free(curr);            
    }
    return ans;
}

c++

const static string MORSE[] = {
        ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
        "....", "..", ".---", "-.-", ".-..", "--", "-.",
        "---", ".--.", "--.-", ".-.", "...", "-", "..-",
        "...-", ".--", "-..-", "-.--", "--.."
};

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        unordered_set<string> seen;
        for (auto &word: words) {
            string code;
            for (auto &c: word) {
                code.append(MORSE[c - 'a']);
            }
            seen.emplace(code);
        }
        return seen.size();
    }
};

python

MORSE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
         "....", "..", ".---", "-.-", ".-..", "--", "-.",
         "---", ".--.", "--.-", ".-.", "...", "-", "..-",
         "...-", ".--", "-..-", "-.--", "--.."]

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        return len(set("".join(MORSE[ord(ch) - 97] for ch in word) for word in words))
        

go

var morse = []string{
    ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
    "....", "..", ".---", "-.-", ".-..", "--", "-.",
    "---", ".--.", "--.-", ".-.", "...", "-", "..-",
    "...-", ".--", "-..-", "-.--", "--..",
}

func uniqueMorseRepresentations(words []string) int {
    set := map[string]struct{}{}
    for _, word := range words {
        trans := &strings.Builder{}
        for _, ch := range word {
            trans.WriteString(morse[ch-'a'])
        }
        set[trans.String()] = struct{}{}
    }
    return len(set)
}

rust

impl Solution {
    pub fn unique_morse_representations(words: Vec<String>) -> i32 {
        let morse = vec![
            ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..",
            "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
            "-.--", "--..",
        ];
        let mut seen = std::collections::HashSet::new();
        words.iter().for_each(|word|{
            let mut code = String::new();
            word.as_bytes().iter().for_each(|c|{
                code.push_str(morse[(c - 97) as usize]);
            });
            seen.insert(code);
        });
        seen.len() as i32
    }
}

typescript

function uniqueMorseRepresentations(words: string[]): number {
    const morse = {"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":"--.."};
    const seen = words.map(word => {
        let code = '';
        for (let i = 0; i < word.length; i++) {
            code += morse[word[i]];
        }
        return code;
    });
    return new Set(seen).size;
};

原题传送门:https://leetcode-cn.com/problems/unique-morse-code-words/


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