leetcode 804. Unique Morse Code Words(String、char、HashSet、ASC2)

本文介绍了一种将英文单词转化为摩斯电码的方法,并通过一个具体示例展示了如何计算一组单词转化为不同摩斯电码组合的数量。利用ASCII码与摩斯电码之间的映射关系,文章提供了一种有效算法来解决这一问题。

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.

题意:

将几个单词转换成摩斯码,返回不同摩斯码的数量

思路:

存储摩斯码,每个单词的每个字母通过ASC2码用当前字母-'a’可以对应摩斯码的位置,将摩斯码append成单词,将单词存入HashSet,因为HashSet不允许重复,直接返回长度

知识点:
  1. String[]数组的赋值是{} 不是[]
    调用时是String[] 不是{}
  2. new HashSet的时候可以不定义长度
  3. foreach中String类型第一个字母大写,String 才是指 java.lang.String 类
    foreach中char类型
  4. String转换为char :
    使用String.charAt(index)(返回值为char)可以得到String中某一指定位置的char。
    使用String.toCharArray()返回值为char[])可以得到将包含整个String的char数组。这样我们就能够使用从0开始的位置索引来访问string中的任意位置的元素。
  5. ASC2码小写字母位置是连续的,所以 ‘字母’-’a’=字母和a的距离,此题就对应morse数组中对应字母的索引
  6. HashSet中添加元素用add(),计算长度用size()
Bug:

此题中HashSet()是String类型,所以最后使用add方法时要先用toString()将StringBuilder()转换String类型才能使用

class Solution {
    public int uniqueMorseRepresentations(String[] words) {
        String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};//{} not[]
        Set<String> ans = new HashSet<>();//words.length
        //String[] arr = (String[])set.toArray(new String[0]);
        for(String word:words){
           // word.toCharArray()
            StringBuilder res = new StringBuilder();
            for(char c : word.toCharArray()){
                res.append(morse[c-'a']);//[] not()
            }
            ans.add(res.toString());//tostring
        }
        return ans.size();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值