唯一摩尔斯密码词(力扣题库)

本文介绍了一个Java程序,该程序将一系列英文单词转换为Morse电码,并计算不同Morse电码表示的唯一数量。通过使用HashMap数据结构,程序能够有效地区分并计数不同的Morse电码字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) {
    uniqueMorseRepresentations(new String[]{"gin", "zen", "gig", "msg"});
}

public static int uniqueMorseRepresentations(String[] words){
    Map<String,String> map = new HashMap<>();
    for (int i = 0; i < words.length; i++) {
        String str =tomoersi(words[i]);
        if (map.get(str)==null){
            map.put(str,str);
        }
    }
    return map.size();
}

public static String tomoersi(String s){
    String str="";
    char[] chars=s.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        switch (chars[i]){
            case 'a':
                str+=".-";
           break;
            case 'b':
                str+="-...";
                break;
            case 'c':
                str+="-.-.";
                break;
            case 'd':
                str+="-..";
                break;
            case 'e':
                str+=".";
                break;
            case 'f':
                str+="..-.";
                break;
            case 'g':
                str+="--.";
                break;
            case 'h':
                str+="....";
                break;
            case 'i':
                str+="..";
                break;
            case 'j':
                str+=".---";
                break;
            case 'k':
                str+="-.-";
                break;
            case 'l':
                str+=".-..";
                break;
            case 'm':
                str+="--";
                break;
            case 'n':
                str+="-.";
                break;
            case 'o':
                str+="---";
                break;
            case 'p':
                str+=".--.";
                break;
            case 'q':
                str+="--.-";
                break;
            case 'r':
                str+=".-.";
                break;
            case 's':
                str+="...";
                break;
            case 't':
                str+="-";
                break;
            case 'u':
                str+="..-";
                break;
            case 'v':
                str+="...-";
                break;
            case 'w':
                str+=".--";
                break;
            case 'x':
                str+="-..-";
                break;
            case 'y':
                str+="-.--";
                break;
            case 'z':
                str+="--..";
                break;
        }
    }

    return str;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值