Skip to content

Commit c463cfd

Browse files
authored
Create 720. Longest Word in Dictionary.py
1 parent 732dac8 commit c463cfd

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#
2+
3+
'''
4+
1. 아이디어 :
5+
백트래킹을 사용합니다.
6+
words를 set으로 관리하여 O(1)로 조회가 가능하도록하고,
7+
""에서 a-z까지 순회하며 값을 붙여넣고, set에 있으면 재귀로 들어가고, 없으면 다음 알파벳으로 넘어갑니다.
8+
9+
2. 시간복잡도 :
10+
O(N * 26 * L) set에 있는 단어 수 * 알파벳 * 단어 길
11+
12+
3. 자료구조/알고리즘 :
13+
백트래킹
14+
15+
'''
16+
class Solution:
17+
def __init__(self):
18+
self.ans = ""
19+
20+
def longestWord(self, words: List[str]) -> str:
21+
words_set = set(words)
22+
23+
def backtrack(word):
24+
for i in range(26):
25+
next_char = chr(i+97)
26+
temp = word + next_char
27+
if temp in words_set:
28+
if len(self.ans) < len(temp):
29+
self.ans = temp
30+
backtrack(temp)
31+
32+
33+
backtrack("")
34+
return self.ans

0 commit comments

Comments
 (0)