题目地址:
https://leetcode.com/problems/unique-morse-code-words/
给定一个字符串数组,代表每个字母对应的摩斯密码。再给定若干单词,求这些单词对应的摩斯密码的个数(需要去重)。
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] codes = {".-", "-...", "-.-.", "-..", ".",
"..-.", "--.", "....", "..", ".---", "-.-",
".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
Set<String> set = new HashSet<>();
for (String word : words) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
sb.append(codes[word.charAt(i) - 'a']);
}
set.add(sb.toString());
}
return set.size();
}
}
时间复杂度 O ( n l ) O(nl) O(nl), n n n为单词个数, l l l为单词最长长度,空间 O ( n l ) O(nl) O(nl)。