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();
        }
    }
    
  • 相关阅读:
    iOS很重要的 block回调
    怎样写具体设计文档
    ORM框架
    RapidXml用法
    【Android Training
    ORACLE触发器具体解释
    LeetCode 131 Palindrome Partitioning
    Git管理工具对照(GitBash、EGit、SourceTree)
    Android下将图片载入到内存中
    怎样破解邮箱password
  • 原文地址:https://www.cnblogs.com/zhuobo/p/10602729.html
Copyright © 2011-2022 走看看