804. 唯一摩尔斯密码词(C++)

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

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

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

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

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

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

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

 

注意:

  • 单词列表words 的长度不会超过 100
  • 每个单词 words[i]的长度范围为 [1, 12]
  • 每个单词 words[i]只包含小写字母。
// uniqueMorseRepresentations.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<vector>
#include<iostream>
using namespace std;


int uniqueMorseRepresentations(vector<string>& words) {
	int count = 0;
	int havecount = 0;
	const string code[26] = { ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.." };
	vector<string> str;
	if (words.empty()) return 0;
	//字符串转化为符号
	for (vector<string>::iterator it = words.begin(); it != words.end(); it++)
	{
		string temp;
		for (int i = 0; i < (*it).length(); i++)
		{
			temp += code[(*it)[i] - 'a'];//查表

		}
		str.push_back(temp);

		cout << *it << endl;
		cout << temp << endl;
	}
	//有相同的字符串则将其置为"NULL",然后进行下一轮的比较
	for (vector<string>::iterator it = str.begin(); it != str.end(); it++)
	{
		if (*it == "NULL" && it != str.end()-1)//统计过的为"NULL",则跳过不在查找
		{
			//it++;
			continue;
		}
		for (vector<string>::iterator iit = it+1; iit != str.end(); iit++)
		{

			if (*iit == *it)
			{
				*iit = "NULL";
				havecount++;
			}
		}
		if(it != str.end()-1)
			*it = "NULL";
		if (havecount)//统计相同的字符串
		{
			count++;
			havecount = 0;
		}
	}
	if (*(str.end() - 1) != "NULL")//最后一个特殊处理
	{
		count += 1;
	}
	cout << "result:"<<count << endl;
	return count;
}

int main()
{
	//vector<string> words = { "gin", "zen", "gig", "msg" };
	//vector<string> words = { "rwjje","aittjje","auyyn","lqtktn","lmjwn","fmekow"};
	vector<string> words = { "vtpke", "vngc", "vnqr", "gbzx", "qvdx" };
	uniqueMorseRepresentations(words);
	getchar();
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值