804. Unique Morse Code Words

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();
}
原文地址:https://www.cnblogs.com/okokabcd/p/9520549.html