|
| 1 | +from bisect import bisect_left, bisect_right |
| 2 | + |
| 3 | +# 값이 [left_value, right_value]인 데이터의 개수를 반환하는 함수 |
| 4 | +def count_by_range(a, left_value, right_value): |
| 5 | + right_index = bisect_right(a, right_value) |
| 6 | + left_index = bisect_left(a, left_value) |
| 7 | + return right_index - left_index |
| 8 | + |
| 9 | +# 모든 단어들을 길이마다 나누어서 저장하기 위한 리스트 |
| 10 | +data = [[] for _ in range(10001)] |
| 11 | +# 모든 단어들을 길이마다 나누어서 뒤집어 저장하기 위한 리스트 |
| 12 | +reversed_data = [[] for _ in range(10001)] |
| 13 | + |
| 14 | +def solution(words, queries): |
| 15 | + answer = [] |
| 16 | + for word in words: # 모든 단어를 접미사 와일드카드 배열, 접두사 와일드카드 배열에 각각 삽입 |
| 17 | + data[len(word)].append(word) |
| 18 | + reversed_data[len(word)].append(word[::-1]) |
| 19 | + |
| 20 | + for i in range(10001): # 이진 탐색을 수행하기 위해 각 단어들 정렬 수행 |
| 21 | + data[i].sort() |
| 22 | + reversed_data[i].sort() |
| 23 | + |
| 24 | + for q in queries: # 쿼리를 하나씩 확인하며 처리 |
| 25 | + if q[0] != '?': # 접미사에 와일드 카드가 붙은 경우 |
| 26 | + res = count_by_range(data[len(q)], q.replace('?', 'a'), q.replace('?', 'z')) |
| 27 | + else: # 접두사에 와일드 카드가 붙은 경우 |
| 28 | + res = count_by_range(reversed_data[len(q)], q[::-1].replace('?', 'a'), q[::-1].replace('?', 'z')) |
| 29 | + # 검색된 단어의 개수를 저장 |
| 30 | + answer.append(res) |
| 31 | + return answer |
0 commit comments