804. Unique Morse Code Words

ぐ巨炮叔叔 提交于 2019-12-06 00:43:34

Question

804. Unique Morse Code Words

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

Solution

题目大意:

根据对应的编码规则将字符串数组中每个字符串编码,这样就得到一个编码后的数组,数组去重后返回数组大小

思路:用set来保存编码后的字符串

Java实现:

public int uniqueMorseRepresentations(String[] words) {
    String[] arr = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
    Set<String> codeSet = new HashSet<>();
    for (String word : words) {
        String code = "";
        for (char c : word.toCharArray()) {
            code += arr[c - 'a'];
        }
        /*if (!codeSet.contains(code)) {
            codeSet.add(code);
        }*/
        codeSet.add(code);
    }
    return codeSet.size();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!