LeetCode暑期刷题打卡——字符串专题day5

208. 实现 Trie (前缀树)

在这里插入图片描述

struct Node{
        bool is_end;
        Node *son[26];
        Node(){
            is_end = false;
            for(int i = 0; i < 26; i ++) son[i] = NULL;
        }
    }*root;
    Trie() {
        root = new Node();
    }
    
    void insert(string word) {
        auto p = root;
        for(auto c : word){
            int u = c - 'a';
            if(p->son[u] == NULL) p->son[u] = new Node();
            p = p->son[u];
        }
        p->is_end = true;
    }
    
    bool search(string word) {
        auto p = root;
        for(auto c : word){
            int u = c - 'a';
            if(p->son[u] == NULL) return false;
            p = p->son[u];
        }
        return p->is_end;
    }
    
    bool startsWith(string prefix) {
        auto p = root;
        for(auto c : prefix){
            int u = c - 'a';
            if(p->son[u] == NULL) return false;
            p = p->son[u];
        }
        return true;
    }

273. 整数转换英文表示

在这里插入图片描述

string small[20] = {"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
                        "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    string decade[10] = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
    string big[4] = {"Billion","Million","Thousand",""};

    string numberToWords(int num) {
        if(!num) return small[0];
        
        string res;
        for(int i = 1e9,j = 0; i > 0; i /= 1000,j ++){
            if(num >= i){
                res += get_part(num/i) + big[j] + ' ';
                num %= i;
            }
        }
        while(res.back() == ' ') res.pop_back();
        return res;
    }

    string get_part(int num){
        string res;
        if(num >= 100){
            res += small[num/100] + " Hundred ";
            num %= 100;
        }
        if(!num) return res;
        if(num >= 20){
            res += decade[num/10] + ' ';
            num %= 10;
        }
        if(!num) return res;
        res += small[num] + ' ';
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值