试着写摩尔斯电码翻译

时间:2013-11-27 10:21:05

标签: java algorithm

import java.util.*;
class Test1{
static int b=0;
static int c=0;
static boolean convert(HashMap h,String l,int len){
//System.out.println(len);
//if(l.substring(0,len+1)
if(len==0)
return true;
for(int i=2;i<=len;i++){
if(h.get(l.substring(0,i))!=null&&(convert(h,l.substring(i,len+1),len-i))){
//System.out.println(h.get(l.substring(0,i)));
//convert(h,l.substring(i,len+1),len-i);

//System.out.println(l.substring(i,len+1));
System.out.print(h.get(l.substring(0,i)));
}
//else if(l.length=len)
//convert(h,l.substring(i-1,len+1));
}
return true;
}


public static void main(String args[]){
HashMap<String,String> h=new HashMap<String,String>();
h.put(".-","a");
h.put("-...","b");
h.put("-.-.","c");
h.put("-..","d");
h.put("-.","n");
h.put(".---","j");
h.put("---","o");
h.put("--","m");
h.put("-..-","x");
h.put("--.","g");
String l="-..-----.";
int len=l.length();
//Output should be njg, dog, xmg xon,naon
convert(h,l,len-1);
}
}

我坚持这个我需要将这些符号转换为英语aplhabets。所以,如果我输入字符串l =“ - 。 - - 。”;输出应该是 njg,dog,xmg xon,naon 。 我试着写转换函数,但我无法解决它。请帮忙

2 个答案:

答案 0 :(得分:0)

这种方法可以解决问题

static void findTranslation(Map<String, String> map, String message, String translation) {
    if (message != null && !message.isEmpty()) {
        for (String key : map.keySet()) {
            if (message.startsWith(key)) {
                String currentTranslation = translation + map.get(key);
                String restOfTheMessage = message.substring(key.length());
                if (!restOfTheMessage.isEmpty()) {
                    findTranslation(map, restOfTheMessage, currentTranslation);
                }
                else {
                    System.out.println(currentTranslation);
                }
            }
        }
    }
}

并在你的主要:

String l="-..-----.";
findTranslation(h, l, "");

将打印:

dt9
dttttn
dttt.z
dttmn
dtmtn
dtm.z
dton
dmttn
dmt.z
dmmn
dotn
do.z
x9
xtttn
xtt.z
xtmn
xmtn
xm.z
xon
tit9
tittttn
tittt.z
tittmn
titmtn
titm.z
titon
timttn
timt.z
timmn
tiotn
tio.z
t2tn
t2.z
tu9
tutttn
tutt.z
tutmn
tumtn
tum.z
tuon
nwttn
nwt.z
nwmn
njtn
nj.z
n1n
na9
natttn
natt.z
natmn
namtn
nam.z
naon

答案 1 :(得分:0)

我假设我在上面评论中的推测是正确的,并且这应该产生对莫尔斯代码字符串的所有可能的解释,其中缺少空格。

一般算法的工作原理如下:

List<String> interpret(String input, int symbolStart, String currentInterpretation) {
    list = new List<String>

    if symbolStart >= input.length
        list.add(currentInterpretation)
        return list;
    end if

    for symbolEnd = symbolStart to input.length - 1
        symbol = input between characters symbolStart and symbolEnd (inclusive)
        if symbol is a valid morse letter:
            letter = the letter that symbol represents
            list.addAll( interpret(input, symbolEnd + 1, currentInterpretation + letter ) );
        end if
    end for

    return list;
}

interpret(input, 0, "");

这是一种递归解决方案,其中算法在每个可能的解释处分支,然后将所有分支的结果组合成单个列表。