zoukankan      html  css  js  c++  java
  • 804. Unique Morse Code Words

    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, "cba" 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 "--...--.".
    

    分析:

    1. 将每一个字符串都转化为摩斯密码;
    2. 使用set去重,返回摩斯密码个数(size());
    class Solution {
        public int uniqueMorseRepresentations(String[] words) {
            String[] code = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};// store the morse code of 'a' ~ 'z'
            Set<String> morseSet = new HashSet<>();// 去重计算个数
            for(String word: words){
                char[] chars = word.toCharArray();// String转化为字符数组
                String morse = "";
                for(char c: chars){// 对于字符数组的每一个字符,Morse+该字符的Morsecode
                    morse += code[c - 'a'];
                }
                morseSet.add(morse);// 该字符串的Morse code如set
            }
            
            return morseSet.size();
        }
    }
    
  • 相关阅读:
    Docker
    Docker
    Linux
    VUE- 前端插件
    小程序中实现 input 搜索框功能
    Vue 中用delete方式进行axios请求接口,请求状态码报415(Unsupported Media Type)
    关于小程序使用map组件,标记markers时报错误(ret is not defined)
    关于element 框架中table表格选中并切换下一页之前选中数据消失的问题
    vue切换路由时报错 uncaught(in promise) Navigation Duplicated 问题
    2019-09-09 JS面试题(持续更新中)
  • 原文地址:https://www.cnblogs.com/zhuobo/p/10602729.html
Copyright © 2011-2022 走看看