【Lintcode】1013. Unique Morse Code Words

題目地址:

https://www.lintcode.com/problem/unique-morse-code-words/description

參考https://blog.csdn.net/qq_46105170/article/details/106213340。代碼如下:

import java.util.HashSet;
import java.util.Set;

public class Solution {
    /**
     * @param words: the given list of words
     * @return: the number of different transformations among all words we have
     */
    public int uniqueMorseRepresentations(String[] words) {
        // Write your code here
        String[] codes = {".-", "-...", "-.-.",
                "-..", ".", "..-.",
                "--.", "....", "..",
                ".---", "-.-", ".-..",
                "--", "-.", "---",
                ".--.", "--.-", ".-.",
                "...", "-", "..-",
                "...-", ".--",
                "-..-", "-.--", "--.."};
    
        Set<String> set = new HashSet<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            sb.setLength(0);
            for (int j = 0; j < word.length(); j++) {
                sb.append(codes[word.charAt(j) - 'a']);
            }
            set.add(sb.toString());
        }
        
        return set.size();
    }
}

時間複雜度O(nl)O(nl),空間O(nl)O(nl)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章