-
Notifications
You must be signed in to change notification settings - Fork 13
/
prefix-code.cpp
42 lines (36 loc) · 967 Bytes
/
prefix-code.cpp
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
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
int main() {
int N, val, maxS(0);
string key, test;
map<string, int> dic;
cin >> N; cin.ignore();
while ( N-- && cin >> key >> val )
{
dic[key] = val; cin.ignore();
if ( maxS < key.size() ) { maxS = key.size(); }
}
cin >> test; cin.ignore();
bool isOk (true);
int st_idx(0 ), cur_idx (-1 );
string cur, res;
while( isOk && ++cur_idx < test.length() )
{
cur += test.at(cur_idx);
if ( cur.size() > maxS )
{
isOk = false;
}
else if ( dic.find( cur ) != dic.end() )
{
res += (char)dic[cur];
cur.clear();
st_idx = cur_idx + 1;
}
}
isOk = cur.empty();
cout << ( isOk ? res : ("DECODE FAIL AT INDEX " + to_string(st_idx)) ) << endl;
}