leetcode 804. Unique Morse Code Words(独特的摩斯码单词)

该博客探讨了一个编程问题,涉及将英文单词转换为摩斯码并计算不同单词的不同摩斯码表示。给定一个单词数组,我们需要计算所有单词经过摩斯码转换后的唯一表示数量。解决方案包括遍历单词,构建每个单词的摩斯码表示,并使用HashSet来存储和计数唯一的摩斯码。博客强调了在处理字符串连接时,StringBuilder相对于String的效率优势。

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

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:

‘a’ maps to “.-”,
‘b’ maps to “-…”,
‘c’ maps to “-.-.”, and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:

[“.-”,“-…”,“-.-.”,“-…”,“.”,“…-.”,“–.”,“…”,“…”,“.—”,“-.-”,“.-…”,“–”,“-.”,“—”,“.–.”,“–.-”,“.-.”,“…”,“-”,“…-”,“…-”,“.–”,“-…-”,“-.–”,“–…”]
Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.

For example, “cab” can be written as “-.-…–…”, which is the concatenation of “-.-.”, “.-”, and “-…”. We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.

Example 1:

Input: words = [“gin”,“zen”,“gig”,“msg”]
Output: 2
Explanation: The transformation of each word is:
“gin” -> “–…-.”
“zen” -> “–…-.”
“gig” -> “–…–.”
“msg” -> “–…–.”
There are 2 different transformations: “–…-.” and “–…–.”.

每个字母对应一个摩斯码,单词的摩斯码是字母摩斯码的拼接。
字符串数组words的单词中,有多少个不同的摩斯码。

思路:

就是简单地把每个单词的摩斯码都拼出来,然后看有几个不同的。
可用HashSet保存单词的摩斯码,重复的也只会保存一个,最后看hashSet的size即可。

拼摩斯码时可以直接用string的拼接,即string1 + string2的形式,
但是注意了,这个耗内存会比StringBuilder要大(但是也能通过测试),
因为String是不可变的对象,每次对String进行操作的时候,都会生成一个新的对象,这会对系统的性能造成影响。
而StringBuilder是对本身进行操作的。

public int uniqueMorseRepresentations(String[] words) {
    HashSet<String> set = new HashSet<>();
    
    String[] codes = new String[]{
       ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
        "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
        "..-","...-",".--","-..-","-.--","--.."
    };
    
    for(String word : words) {
        StringBuilder code = new StringBuilder();
        for(int i = 0; i < word.length(); i++) {
            int idx = word.charAt(i) - 'a';
            code.append(codes[idx]);
        }
        set.add(code.toString());
    }
    
    return set.size();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值