|
| 1 | +#include <string> |
| 2 | +#include <vector> |
| 3 | +#include <iostream> |
| 4 | +#include <algorithm> |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +bool cmp_word(string a, string b) { |
| 8 | + return a.length() < b.length(); |
| 9 | +} |
| 10 | + |
| 11 | +struct info_word { |
| 12 | + bool end; |
| 13 | + int depth; |
| 14 | + info_word *next_info[26]; |
| 15 | +}; |
| 16 | + |
| 17 | +int solution131(vector<string> words) { |
| 18 | + int answer = 0; |
| 19 | + info_word dic[26] = { {false,0,NULL}, }; // 모든 알파벳 초기화 |
| 20 | + sort(words.begin(), words.end(), cmp_word); // 짧은 순 정렬 |
| 21 | + |
| 22 | + for (int i = 0; i < words.size(); ++i) { |
| 23 | + info_word *next = &dic[words[i][0]-'a']; // 단어의 첫 알파벳을 루트로 시작 |
| 24 | + |
| 25 | + for (int j = 0; j < words[i].size(); ++j) { // 단어의 길이만큼 계속 info 생성해서 저장 |
| 26 | + if (next->depth == 1) // 이미 검색된 적 있으면 |
| 27 | + ++answer; |
| 28 | + |
| 29 | + next->depth++; |
| 30 | + if (next->depth > 1) // 그 뒷 글자가 있다면 |
| 31 | + answer++; |
| 32 | + |
| 33 | + if (next->end == true) { // 마지막 글자였다면 |
| 34 | + answer--; // 그 전 글자를 쳤을 때 자동완성됨 |
| 35 | + next->end = false; |
| 36 | + } |
| 37 | + |
| 38 | + if (j == words[i].size() - 1) { // 단어의 끝 글자라면 |
| 39 | + if (next->depth == 1) |
| 40 | + next->end = true; |
| 41 | + break; |
| 42 | + } |
| 43 | + if (next->next_info[words[i][j + 1] - 'a'] == NULL) // 다음 글자 정보가 없다면 |
| 44 | + next->next_info[words[i][j + 1] - 'a'] = new info_word({ 0,false,NULL }); |
| 45 | + |
| 46 | + next = next->next_info[words[i][j + 1] - 'a']; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return answer+words.size(); |
| 51 | +} |
0 commit comments