https://programmers.co.kr/learn/courses/30/lessons/17685
#include <string>
#include <vector>
#include <map>
using namespace std;
class Trie {
private:
int count = 0;
map<char,Trie *> child;
public:
void insert(string str) {
Trie *now = this;
for (int i = 0; i < str.size(); i++) {
if (now->child[str[i]] == nullptr) {
now->child[str[i]] = new Trie;
}
now = now->child[str[i]];
now->count++;
}
}
int AutoComplete(string str) {
Trie *now = this->child[str[0]];
int index = 1;
for (int i = 1; i < str.size(); i++) {
if (now->count > 1) {
now = now->child[str[i]];
index++;
}
}
return index;
}
};
int solution(vector<string> words) {
int answer = 0;
Trie root;
for (int i = 0; i < words.size(); i++) {
root.insert(words[i]);
}
for (int i = 0; i < words.size(); i++) {
answer += root.AutoComplete(words[i]);
}
return answer;
}
'프로그래머스' 카테고리의 다른 글
멀리 뛰기 C++ (0) | 2022.03.25 |
---|---|
스티커 모으기(2) C++ (0) | 2022.03.25 |
단속카메라 C++ (0) | 2022.03.25 |
섬 연결하기 C++ (0) | 2022.03.25 |
순위 C++ (0) | 2022.03.24 |