【问题标题】:Comparing a string to a value in the Map<Character, String> and return its' key将字符串与 Map<Character, String> 中的值进行比较并返回其键
【发布时间】:2018-11-16 18:23:45
【问题描述】:

大家好!

我有一个映射,键为字符,值为字符串,如下所示(Baconian Cipher):

public class MyClass {

private static final Map<Character, String> cipheredAlphabet;
    static {
        cipheredAlphabet = new HashMap<Character, String>();
        cipheredAlphabet.put('a', "AAAAA");
        cipheredAlphabet.put('s', "BAABA");
    }
}

我有一个如下所示的字符串:

String encodedMessage = "BAABAAAAAA";

我想一次迭代 5 个字母:

StringBuilder decodedMessage = new StringBuilder();
for(int i=0; i<encodedMessage.length(); i+=5) {
    String fiveLetters = encodedMessage.substring(i, i+5);
    // compare five letters to values and append the corresponding key

}

我如何将这五个字母与我的地图中的值进行比较,并在我的 StringBuilder 中附加一个相应的键?

预期输出:

sa

使用文档中的信息,我想出了如下内容:

StringBuilder decodedMessage = new StringBuilder();
    for(int i=0; i<encodedMessage.length(); i+=5) {
        String fiveLetters = encodedMessage.substring(i, i+5);
        // pseudo code starts from this point
        for(Map.Entry<Character, String> entry: cipheredAlphabet.entrySet()) {
            if(cipheredAlphabet.getValue().equals(fiveLetters))
            decodedMessage.append(cipheredAlphabet.getKey());

【问题讨论】:

    标签: java hashmap iteration


    【解决方案1】:
    for(Map.Entry<Character, String> entry: cipheredAlphabet.entrySet()) {
        if(entry.getValue().equals(fiveLetters)) {
            ecodedMessage.append(cipheredAlphabet.getKey());
            break;
        }
    }
    

    但我认为在你的地图中交换键和值要好得多。

    public class MyClass {
    
        private static final Map<String, Character> MAP = new HashMap<>();
    
        static {
            MAP.put("AAAAA", 'a');
            MAP.put("BAABA", 's');
        }
    
        public String decode(String msg) {
            if (msg == null || msg.length() % 5 != 0)
                throw new IllegalArgumentException("Message length should be a multiple of 5");
    
            StringBuilder buf = new StringBuilder();
    
            for (int i = 0; i < msg.length(); i += 5) {
                String letters = msg.substring(i, i + 5);
                Character ch = MAP.get(letters);
    
                if (ch == null)
                    throw new IllegalArgumentException("Letters '" + letters + "' not found in local map");
    
                buf.append(ch);
            }
    
            return buf.toString();
        }
    }
    

    【讨论】:

    • 非常感谢!它有效,即使我不得不更改为:decodedMessage.append(entry.getKey());写作时:decodedMessage.append(cipheredAlphabet.getKey());编译错误会弹出:)
    • 感谢您的意见和提供的例子!我会尝试用你的方式玩它:)
    • 编码和解码都需要Map。或者某种BiMap
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2021-09-04
    • 2020-03-23
    相关资源
    最近更新 更多