leetcode:唯一摩尔斯密码词

本文介绍了一种将英文字符串转换为对应的摩尔斯电码表示的方法,并通过具体实现展示了如何利用哈希表来确保不同字符串转换后的摩尔斯电码表示的唯一性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: “a” 对应 “.-“, “b” 对应 “-…”, “c” 对应 “-.-.”, 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[“.-“,”-…”,”-.-.”,”-..”,”.”,”..-.”,”–.”,”….”,”..”,”.—”,”-.-“,”.-..”,”–”,”-.”,”—”,”.–.”,”–.-“,”.-.”,”…”,”-“,”..-“,”…-“,”.–”,”-..-“,”-.–”,”–..”]

    public static int uniqueMorseRepresentations(String[] words) {
        if(words == null || words.length <= 0){
            return 0;
        }
        if(words.length == 1){
            return 1;
        }
        for(String word : words){
            word = word.toLowerCase();
        }
        Map<String, String> map = new HashMap<String, String>();
        for(String word : words){
            word = words2Morse(word);
            map.put(word, word);
        }
        return map.size();
    }

    public static String words2Morse(String word){
        if(word == null || word == ""){
            return "";
        }
        word = word.replace("a", ".-").replace("b", "-...").replace("c", "-.-.").replace("d", "-..").replace("e", ".")
                .replace("f", "..-.").replace("g", "--.").replace("h", "....").replace("i", "..").replace("j", ".---")
                .replace("k", "-.-").replace("l", ".-..").replace("m", "--").replace("n", "-.").replace("o", "---")
                .replace("p", ".--.").replace("q", "--.-").replace("r", ".-.").replace("s", "...").replace("t", "-")
                .replace("u", "..-").replace("v", "...-").replace("w", ".--").replace("x", "-..-").replace("y", "-.--").replace("z", "--..");
        return word;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值