【LeetCode】804. Unique Morse Code Words

题目:


简述题目:

    题目中给出了一个摩斯密码的对应数组,也就是每个字母分别对应的摩斯密码,然后给出一组单词,求最终不同的摩斯密码的个数(因为有些字母的摩斯密码的组合可能会相同)

思路:

    遍历,然后生成每个单词的莫斯密码,存储,求个数

    我一开始用了hashmap,还统计了每个摩斯密码出现的个数,但是其实并么有这个必要,只需要知道一共有多少个不同的就行了,所以后来改用了hashset,可以直接过滤到相同的元素,最终直接范围set.size()就行了

代码:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class uniqueMorseRepresentations804 {
    public static int uniqueMorseRepresentations(String[] words) {
//    	这里使用set
    	String morseString = "";
    	String[] morseCode = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    	Set<String> set = new HashSet<>();
    	for(int i = 0; i < words.length; i++){
    		morseString = "";
    		for(int j = 0; j < words[i].length();j++){
    		   morseString += morseCode[words[i].charAt(j) - 'a'];
    		}
    		set.add(morseString);
    	
    	}
    	return set.size();
//    	这里用了hashmap
//    	String morseString = "";
//    	String[] morseCode = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
//    	Map<String,Integer> map = new HashMap<>();
//    	for(int i = 0; i < words.length; i++){
//    		morseString = "";
//    		for(int j = 0; j < words[i].length();j++){
//    		   morseString += morseCode[words[i].charAt(j) - 'a'];
//    		}
//    		if(map.containsKey(morseString)){
//    			map.put(morseString, map.get(morseString)+1);
//    		}else{
//    			map.put(morseString, 1);
//    		}
//    	}
//    	return map.size();

    }
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] words = {"gin", "zen", "gig", "msg"};
		System.out.println(uniqueMorseRepresentations(words));
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值