일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 구현
- greedy
- Two Pointers
- SinglyLinkedList
- graph
- Medium
- array
- Easy
- String
- ArrayList vs LinkedList
- heap
- 광연자동차운전면허학원
- Leedcode
- 자료구조
- stack
- hash
- Hashtable
- LinkedList
- DailyLeetCoding
- BFS
- python3
- dfs
- leetcode
- VCS
- Union Find
- Java
- A* Algorithm
- hash table
- sorting
- Bellman-Ford
Archives
- Today
- Total
Min IT's Devlog
[python3] 804. Unique Morse Code Words 본문
풀이 일자: 22.08.17
난이도: [Easy]
문제 내용
여러 단어가 담겨있는 words 배열의 각각의 단어의 Unique한 조합이 몇 개인지 구하는 문제였다.
"gin" -> "--...-."
"zen" -> "--...-."
→ 이런식으로 다른 문자더라도 같은 모스부호 조합이 나올 수 있다.
문제 해결 흐름
1. 우선 각 alphabet마다의 모스부호의 규칙이 따로 없기 때문에 해당 정보를 미리 저장해두어야겠다.
→ 배열 형식으로 저장한다.
2. Unique한 조합을 찾기 때문에 미리 이전에 나왔던 모스부호 조합에 대한 정보를 저장해두어야겠다.
→ 만약 나오지 않았다면 갯수를 +1하면서 해당 정보를 저장한다.
3. 앞서 배열정보로 저장해둔 각 문자별 모스부호의 접근 방식은 어떻게 하면 좋을까?
→ 자주 사용하는 방식인 ascii code의 번호을 인덱스로 사용하자.
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morseTable = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
existArr = list()
ans = 0
for word in words:
morseCode = ""
for letter in word:
idx = ord(letter) - ord('a')
morseCode += morseTable[idx]
if morseCode not in existArr:
ans += 1
existArr.append(morseCode)
return ans
다른 해결 방식
1. 기존에는 array에서 해당 모스부호조합이 있는지 확인했는데 다른 자료구조를 사용하면 더 편하지 않을까?
→ 중복을 허용하지 않는 set을 사용한다면 중복되더라도 add하는 과정에서 알아서 안들어가겠지.
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morseTable = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
existSet = set()
for word in words:
morseCode = ""
for letter in word:
idx = ord(letter) - ord('a')
morseCode += morseTable[idx]
existSet.add(morseCode)
return len(existSet)
문제 링크
'코테 > LeetCode(Solve)' 카테고리의 다른 글
[python3] 967. Numbers With Same Consecutive Differences (0) | 2022.09.03 |
---|---|
[python3] 637. Average of Levels in Binary Tree (0) | 2022.09.03 |
[python3] 1448. Count Good Nodes in Binary Tree (0) | 2022.09.01 |
[python3] 1338. Reduce Array Size to The Half (0) | 2022.08.18 |
[python3] 387. First Unique Character in a String (0) | 2022.08.16 |
Comments