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

    804. Unique Morse Code Words(唯一摩尔斯密码词)

    题目:

      

      国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-""b"对应 "-...""c" 对应 "-.-.", 等等。

      为了方便,所有26个英文字母对应摩尔斯密码表如下:

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

      给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。

      返回我们可以获得所有词不同单词翻译的数量。

      例如:
      输入: words = ["gin", "zen", "gig", "msg"]
      输出: 2
      解释: 
      各单词翻译如下:
      "gin" -> "--...-."
      "zen" -> "--...-."
      "gig" -> "--...--."
      "msg" -> "--...--."
    
      共有 2 种不同翻译, "--...-." 和 "--...--.".

      注意:

      •  单词列表words 的长度不会超过 100
      •  每个单词 words[i]的长度范围为 [1, 12]
      •  每个单词 words[i]只包含小写字母。

    思路:

      这道题的思路比较清晰,对于每一个word,将之转换为摩斯电码,使用hashset存储,最后统计这个散列表里面的值即可。

    代码:

     1     public static int uniqueMorseRepresentations(String[] words) 
     2     {
     3         String[] codes={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
     4         HashSet<String> hashset=new HashSet<String>();
     5         for (int i = 0 ;i < words.length;i++) 
     6         {
     7             String word = words[i];
     8             StringBuilder sc=new StringBuilder("");
     9             for(int j = 0; j < word.length(); j++)
    10             {
    11                 sc.append(codes[word.charAt(j)-97]);
    12             }
    13             hashset.add(sc.toString());
    14         }
    15         return hashset.size();
    16     }
    View Code
  • 相关阅读:
    ZOJ 3332 Strange Country II
    ZOJ 3331 Process the Tasks(双塔DP)
    ZOJ 3326 An Awful Problem(模拟)
    HDU 1796 How many integers can you find(容斥原理)
    HDU 4059 The Boss on Mars(容斥原理)
    HDU 4135 Co-prime(容斥原理)
    HDU 5677 ztr loves substring(回文串加多重背包)
    CodeForces 668B Little Artem and Dance
    CodeForces 667A Pouring Rain
    Java实现 LeetCode 764 最大加号标志(暴力递推)
  • 原文地址:https://www.cnblogs.com/blogxjc/p/10886198.html
Copyright © 2011-2022 走看看