Using the features of HashSet to solve the "unique Morse code word" problem

8. Unique Morse code word

8.1. Title requirements

​ International Morse cipher defines a standard encoding that maps each letter to a string consisting of a series of dots and dashes, such as:

'a' corresponds to ".-",
'b' corresponds to "-…",
'c' corresponds to "-.-.", and so on.
For convenience, the Morse code table for all 26 English letters is as follows:

[".-","-...","-.-.","-...",".","...-.","–.","...","...",".-" ,"-.-",".-…","–","-.","—",".–.","–.-",".-.","…","- ","…-","…-",".–","-…-","-.–","–…"]
​ gives you a string array words, each word can be written as each The letters correspond to combinations of Morse code.

For example, “cab” can be written as “-.-…–…”, (that is, the combination of “-.-.” + “.-” + “-…” strings). We refer to such a connection process as word translation.
​ Perform word translation on all words in words and return the number of different word translations.

示例 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] 由小写英文字母组成

Source: LeetCode
Link: https://leetcode-cn.com/problems/unique-morse-code-words

8.2. Problem solving ideas

​​ First define a Morse cipher dictionary, then take out each word in the string array and loop in turn, convert each letter in each word and then splicing, and then spliced ​​Morse cipher Save it to HashSet (at this time, we use the uniqueness of HashSet, only one type is stored in HashSet once, so there is no duplication of elements in HashSet), and finally return the size of HashSet.

8.3. Algorithms

class Solution {
    
    
    public int uniqueMorseRepresentations(String[] words) {
    
    
        //先定义一个摩尔斯密码字典
        String[] MORSE = {
    
    ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};

        Set<String> set = new HashSet<>();
        //将字符串数组中的每个单词取出来并依次进行循环
        for(String word : words){
    
    
            //使用StringBuilder将转换的密码储存起来
            StringBuilder sb = new StringBuilder();
            //使用每个单词的长度进行循环
            for(int i = 0;i < word.length();i++){
    
    
                //将每个单词中的每个字母取出来
                char c = word.charAt(i);
                //将每个单词转换成摩尔斯密码并进行拼接
                //MORSE[c - 'a']将每个单词进行转换
                //code.append()将转换的单词进行拼接
                sb.append(MORSE[c - 'a']);
            }
            //将转换后的结果存入到HashSet中,这里我们使用到了HashSet的唯一性
            //因为HashSet中的值是唯一的,所以重复的类型会被去掉
            set.add(sb.toString());
        }
        //最后,我们只需要返回HashSet的大小即可
        return set.size();
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124108920