LeetCode-Unique Morse Code Words

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82529572

Description:
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:

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

Now, given a list of words, 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 “-.-.” + “-…” + “.-“). We’ll call such a concatenation, the transformation of a word.

Return the number of different transformations among all words we have.

Example:

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 “–…–.”.

Note:

The length of words will be at most 100.
Each words[i] will have length in range [1, 12].
words[i] will only consist of lowercase letters.

题意:给定一张表,定义了摩斯密码中26个小写字母的映射表;定义级联为将一个单词的所有字母按照映射表表示后所连接在一起的结果;现要求根据给定的一个字符串数组,找出级联后不相同的字符串的个数;

解法:因为最后要返回的是级联不相同的个数,因此我们可以用一个集合来存储每次级联后的结果,最后返回集合的大小即可;要得到级联可以根据给定的映射表将单词的每个字母映射结果连接在一起;这里我们使用了StringBuilder而不是String,是因为使用String的话相当于每次都要创建一个String对象,会造成资源的浪费,因此使用了StringBuilder;

Java
class Solution {
    public int uniqueMorseRepresentations(String[] words) {
        String[] table = new String[] {".-","-...","-.-.","-..",".","..-.","--.","....","..",
                                      ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
                                      "...","-","..-","...-",".--","-..-","-.--","--.."};
        Set<String> transformation = new HashSet<>();
        for (String word : words) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < word.length(); i++) {
                sb.append(table[word.charAt(i) - 'a']);
            }
            if (!transformation.contains(sb.toString())) {
                transformation.add(sb.toString());
            }
        }
        return transformation.size();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82529572