• 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();
        }
    }
    
  • 相关阅读:
    子页面与父页面相互调用函数、元素、变量
    springboot项目多数据源及其事务
    mybatis逆向工程
    PageHelper 分页插件
    spring boot 在eclipse中打war包,及jar包
    Spring 定时任务之 @Scheduled cron表达式
    发送邮件
    spring+springmvc+hibernate 框架搭建
    MySQL驱动和数据库字符集设置不搭配
    Oracle与MySQL区别
  • 原文地址:https://www.cnblogs.com/zhuobo/p/10602729.html
Copyright © 2020-2023  润新知