Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
Tags
- 유니온 파인드
- 완전탐색
- 동적계획법
- 세그먼트 트리
- 스택
- CS
- 투 포인터
- 에라토스테네스의 체
- 문자열
- Effective Java
- 수학
- 구현
- mst
- 시뮬레이션
- BFS
- 프로그래머스
- 위상정렬
- swea
- Kotlin
- dfs
- JUnit 5
- 알고리즘
- Network
- 이분탐색
- 플로이드-와샬
- 후니의 쉽게 쓴 시스코 네트워킹
- 백준
- 백트래킹
- 그리디
- java
Archives
반갑습니다!
[프로그래머스] 자동완성 본문
풀이
Trie
자료구조를 살짝 변형하여 해결하였다. 자료구조 내부에 자식의 개수를 저장하여 탐색을 끝까지 안해도 단어를 찾을 수 있도록 구현하였다.
코드
#include <string>
#include <vector>
using namespace std;
struct Trie {
int child_cnt;
bool end;
Trie* child[26];
Trie() {
end = false;
child_cnt = 0;
fill(child, child + 26, nullptr);
}
~Trie() {
for (int i = 0; i < 26; i++)
if (child[i]) delete child[i];
}
void insert(const string& word, int idx) {
char key = word[idx];
if (key == '\0') end = true;
else {
int next = key - 'a';
if (!child[next]) child[next] = new Trie;
child[next]->child_cnt++;
child[next]->insert(word, idx + 1);
}
}
int find(const string& word, int idx) {
int key = word[idx] - 'a';
// 단어를 끝까지 탐색한 경우는 단어 길이를 그대로 리턴
if (end && word[idx] == '\0') return word.length();
// child의 개수가 1이라는 것은 자동 완성이 가능하다는 것이므로 입력한 길이만큼 리턴해준다
if (child[key]->child_cnt == 1) return idx + 1;
// 자동완성이 불가능한경우 다음 글자로 넘어간다
return child[key]->find(word, idx + 1);
}
};
int solution(vector<string> words) {
int answer = 0;
Trie* root = new Trie;
for (string str : words)
root->insert(str, 0);
for (string str : words)
answer += root->find(str, 0);
return answer;
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 10973 이전 순열 (0) | 2020.04.23 |
---|---|
[백준] 14425 문자열 집합 (0) | 2020.04.23 |
[백준] 5052 전화번호 목록 (0) | 2020.04.23 |
[백준] 2234 성곽 (0) | 2020.04.22 |
[백준] 1600 말이 되고픈 원숭이 (0) | 2020.04.22 |