LeetCode-804. 唯一摩尔斯密码词

241 篇文章 1 订阅
206 篇文章 0 订阅

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

'a' 对应 ".-" ,
'b' 对应 "-..." ,
'c' 对应 "-.-." ,以此类推。
为了方便,所有 26 个英文字母的摩尔斯密码表如下:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给你一个字符串数组 words ,每个单词可以写成每个字母对应摩尔斯密码的组合。

例如,"cab" 可以写成 "-.-..--..." ,(即 "-.-." + ".-" + "-..." 字符串的结合)。我们将这样一个连接过程称作 单词翻译 。
对 words 中所有单词进行单词翻译,返回不同 单词翻译 的数量。

示例 1:

输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释: 
各单词翻译如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

共有 2 种不同翻译, "--...-." 和 "--...--.".
示例 2:

输入:words = ["a"]
输出:1
 

提示:

1 <= words.length <= 100
1 <= words[i].length <= 12
words[i] 由小写英文字母组成

#include<iostream>
#include<unordered_map>
#include<vector>
using namespace std;

//a, b, c, d, e, f, g, h, i, j, k,l, m, n, o, p, q, r, s, t, u, v, w, x, y, z

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        unordered_map<char, string> chHash;
        unordered_map<string, int> wordHash;

        vector<char> alpha = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k',
            'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

        vector<string> alphaTxt = { ".-","-...","-.-.","-..",".","..-.",
            "--.","....","..",".---","-.-",".-..",
            "--","-.","---",".--.","--.-",".-.","...",
            "-","..-","...-",".--","-..-","-.--","--.."};

        for (int i = 0; i < alpha.size(); i++) {
            chHash[alpha[i]] = alphaTxt[i];
        }

        for (int i = 0; i < words.size(); i++) {
            string word;
            for (char c : words[i]) {
                word += chHash[c];
            }
            if (wordHash.count(word) != 0) {
                wordHash[word]++;
            }
            else {
                wordHash[word] = 1;
            }
        }

        return wordHash.size();

    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值