Version #1 HashSet
Time O(ML) - M is number of words, L is the average length of words
Space O(ML)
Runtime: 2 ms, faster than 99.55% of Java online submissions for Unique Morse Code Words.
Memory Usage: 39.8 MB, less than 99.94% of Java online submissions for Unique Morse Code Words.
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] map = new String[]{
".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."
};
Set<String> visited = new HashSet<>();
for (String word : words) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
sb.append(map[word.charAt(i) - 'a']);
}
visited.add(sb.toString());
}
return visited.size();
}
}
一刷
90.21 %
class Solution {
public int uniqueMorseRepresentations(String[] words) {
if (words == null || words.length == 0) return 0;
String[] dict = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
Set<String> set = new HashSet<>();
StringBuilder sb = new StringBuilder();
for (String word : words) {
for (int i = 0; i < word.length(); i++) {
sb.append(dict[word.charAt(i) - 'a']);
}
set.add(sb.toString());
sb.setLength(0);
}
return set.size();
}
}
No comments:
Post a Comment