Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trie #15

Merged
merged 4 commits into from
Sep 23, 2020
Merged

Trie #15

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions trie.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
struct trie
{
int conv(char c)// 상황에 따라 잘 처리해준다.
{
return c - 'a';
}
struct vertex
{
int nxt[26];
int finish; // if not finish, -1
//0based를 가정하는 것
vertex()
{
memset(nxt, -1, sizeof nxt);
finish = -1;
}
};
vector<vertex> data;
int head;//data[head]: head의 vertex
int size; // 단어의 총 개수
trie(int cap = 30'000)//trie자체가 이미 용량을 많이 잡아먹음으로 생성자에서 cap을 잘 지정해줌으로써 매모리를 아낀다.
{
data.reserve(cap);
head = 0;
size = 0;
data.push_back(vertex());
}
void add(const char* str)
{
int v_idx = head;
for (int idx = 0; str[idx]; ++idx)
{
if (data[v_idx].nxt[conv(str[idx])] == -1)
{
data[v_idx].nxt[conv(str[idx])] = data.size();
data.push_back(vertex());
}
v_idx = data[v_idx].nxt[conv(str[idx])];
}
data[v_idx].finish = size++;//만약 중복된 단어가 들어올 수 있다면, 각 노드별로 count변수를 만들어야 한다.
}
int retrieve(const char* str) //찾지 못하면 -1, 찾았다면 add되었던 순서를 리턴(0부터 시작)
{
int v_idx = head;
for (int idx = 0; str[idx]; ++idx)
{
if (data[v_idx].nxt[conv(str[idx])] == -1) return -1;
v_idx = data[v_idx].nxt[conv(str[idx])];
}
return data[v_idx].finish;
}
};