zoukankan      html  css  js  c++  java
  • 820. 单词的压缩编码

    820. 单词的压缩编码

    字典树,将字符串首先按照长度进行排序,然后将字符串倒序插入到字典树中,在插入的时候加一个判断语句,

    如果是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;
        }
    };

     

  • 相关阅读:
    产品微谈
    SVN回滚机制
    super究竟是个啥?
    PM12条
    CocoaPods初体验
    UIView局部点击
    Memory cycles about Block
    About "self"
    openfire学习(一)
    WPF菜单和布局(2)
  • 原文地址:https://www.cnblogs.com/letlifestop/p/12587006.html
Copyright © 2011-2022 走看看