zoukankan      html  css  js  c++  java
  • 804. 唯一摩尔斯密码词『简单』

    题目来源于力扣(LeetCode

    一、题目

    804. 唯一摩尔斯密码词

    题目相关标签:字符串

    注意:

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

    二、解题思路

    1. 遍历 words 单词列表,对于数组中的每个单词进行遍历

    2. 字母字符在哈希数组中找到其对应的摩斯密码

    3. 每次遍历得到的摩斯密码存储到缓冲字符串中

    4. 遍历完每一个单词,都将缓冲字符串添加到 set 集合中,通过 set 集合的特性来实现去重的效果

    5. 最终 set 集合的大小即是不同摩斯密码的个数

    三、代码实现

    public static int uniqueMorseRepresentations(String[] words) {
        // 据题意:26个英文字母对应摩尔斯密码表如下
        String[] trans = {".-", "-...", "-.-.", "-..", ".", "..-.",
                          "--.", "....", "..", ".---", "-.-", ".-..",
                          "--", "-.", "---", ".--.", "--.-", ".-.",
                          "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
    
        Set<String> set = new HashSet<>();
        for (String word : words) {
            StringBuilder sb = new StringBuilder();
            // 遍历单词中的字符
            for (int i = 0; i < word.length(); i++) {
                int index = word.charAt(i) - 'a';
                // 将字符对应的摩斯密码添加到字符串中
                sb.append(trans[index]);
            }
            // 最终的字符串存储到 set 中,通过 set 集合实现去重效果
            set.add(sb.toString());
        }
        // 最终 set 中的大小即不同的单词翻译
        return set.size();
    }
    

    四、执行用时

    五、部分测试用例

    public static void main(String[] args) {
        String[] words = {"gin", "zen", "gig", "msg"};  // output:2
        int result = uniqueMorseRepresentations(words);
        System.out.println(result);
    }
    
  • 相关阅读:
    纯CSS实现自动轮播,CSS变量的定义与使用,计算属性的使用
    input:file样式怎样修改
    Div转为Canvas简直不要太好玩~~~
    oracle nvl2函数
    oracle 子查询
    oracle 分组函数执行分析
    oracle外部表
    oracle USING 用法
    面向对象进阶
    面向对象基础
  • 原文地址:https://www.cnblogs.com/zhiyin1209/p/12969117.html
Copyright © 2011-2022 走看看