力扣剑指offer第22天 前缀和

本文介绍了三种编程问题的解决方案:1) 最短单词编码,通过删除子字符串实现;2) 单词之和,利用前缀匹配查找;3) 最大异或值,使用哈希集合优化查找过程。这些方法展示了在字符串处理和搜索算法中的巧妙应用。
摘要由CSDN通过智能技术生成

65)最短的单词编码

class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
      unordered_set<string> good(words.begin(), words.end());
      for(auto word : words){
        for(int k=1; k<word.size(); k++){
          good.erase(word.substr(k));
        }
      }
      int ans = 0;
      for(auto str : good){
        ans += str.size()+1;
      }
      return ans;
    }
};

66)单词之和

class MapSum {
public:
    unordered_map<string, int> map;
    /** Initialize your data structure here. */
    MapSum() {}
    
    void insert(string key, int val) {
      map[key] =val;
    }
    
    int sum(string prefix) {
      int ans = 0;
      for(auto [key, val] : map){
        if(key.substr(0, prefix.size()) == prefix) ans += val;
      }
      return ans;
    }
};

67)最大的异或

class Solution{
public:
    int findMaximumXOR(vector<int>& nums){
        int HIGHBIT = 30;
        int x = 0;
        for(int k=HIGHBIT; k>=0; k--){
            unordered_set<int> seen;
            for(auto num : nums){
                seen.insert(num>>k);
            }
            int x_next = x*2 + 1;
            bool found = false;
            for(auto& num :nums){
              if(seen.count(x_next^(num>>k))) {
                found = true;
                break;
              }
            }
            if(found) x = x_next;
            else x = x_next-1;
          }
          return x;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值