字典树,将字符串首先按照长度进行排序,然后将字符串倒序插入到字典树中,在插入的时候加一个判断语句,
如果是ch[p][str[i] - 'a'] == 0的话,就代表需要在字典树上插入新的值,所以在这里可以打一个标志位
class Solution {
public:
int ch[20000 + 10][30];
int cnt = 0;
int add(string str) {
int i, len, p = 0;
bool k = 0;
len = str.size();
for(i = len - 1; i >= 0; i--) {
if(!ch[p][str[i] - 'a']) {
k = 1;
ch[p][str[i] - 'a'] = ++cnt;
}
p = ch[p][str[i] - 'a'];
}
return k == 1 ? len + 1 : 0;
}
int minimumLengthEncoding(vector<string>& words) {
int i, j, len, ans = 0;
len = words.size();
if(!len) {
return ans;
}
memset(ch, 0, sizeof(ch));
sort(words.begin(), words.end(), [](string &t1, string &t2){
return t1.size() > t2.size();
});
for(i = 0; i < len; i++) {
// cout << i << " " << words[i] << endl;
ans += add(words[i]);
}
return ans;
}
};