1. 程式人生 > >LeetCode 804 唯一摩爾斯密碼詞

LeetCode 804 唯一摩爾斯密碼詞

size system eset 遍歷字符串 length bsp void pri pack

package com.lt.datastructure.Set;
import java.util.TreeSet;
/*
 * 一個摩斯碼,對應一個字母。返回我們可以獲得所有詞不同單詞翻譯的數量。
 *  遍歷字符串,word.charAt(i)-‘a‘獲得當前字符所對應的索引,添加到StringBuilder容器。
 *  用集合去重
 *  返回集合size
 */
public class LeetCode804 {
    
    public static int uniqueMorseRepresentations(String[] words) {
        
        String[] codes 
= {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; TreeSet<String> set = new TreeSet<>(); for(String word : words ){ StringBuilder res = new
StringBuilder(); for(int i=0 ; i<word.length() ; i++){ res.append(codes[word.charAt(i)-‘a‘]); } System.out.println(res.toString()); set.add(res.toString()); } return set.size(); } public static void main(String[] args) { String[] words
= {"abbc","axxx","bbcs"}; System.out.println(uniqueMorseRepresentations(words)); } }

LeetCode 804 唯一摩爾斯密碼詞