算法刷题计划(十八)比较含退格的字符串、区间列表的交集、找到字符串中所有字母异位词

22 篇文章 0 订阅
20 篇文章 0 订阅

一、比较含退格的字符串

  • 题目:
    在这里插入图片描述
  • 题解:
class Solution {
public:
    bool backspaceCompare(string s, string t) {
        return rebuildStr(s)==rebuildStr(t);
    }
    string rebuildStr(string str){
        string s;
        for(const auto&pr:str){
            if(pr!='#'){
                s.push_back(pr);
            }else if(!s.empty()){
                s.pop_back();
            }
        }
        return s;
    }
};

二、区间列表的交集

  • 题目
    在这里插入图片描述
  • 题解:
class Solution {
public:
    vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
        if(firstList.empty()||secondList.empty())   return vector<vector<int>>{};
        int i=0,j=0;
        vector<vector<int>>v;
        while(i<firstList.size()&&j<secondList.size()){
            int leftMax=max(firstList[i][0],secondList[j][0]);
            int rightMin=min(firstList[i][1],secondList[j][1]);
            if(leftMax<=rightMin){
                v.push_back({leftMax,rightMin});
            }
            if(firstList[i][1]<secondList[j][1]){
                i++;
            }else{
                j++;
            }
        }
        return v;
    }
};

三、找到字符串中所有字母异位词

  • 题目:
    在这里插入图片描述

  • 题解:

  • 方法一(暴力+哈希,超时):

        int pLen=p.size();
        int sLen=s.size();
        if(pLen>sLen)   return {};
        unordered_map<char,int>mp;
        for(const auto&pr:p){
            mp[pr]++;
        }
        vector<int>index;
        for(int i=0;i<sLen-pLen+1;i++){
            unordered_map<char,int>copy;
            for(int j=0;j<p.size();j++){
                copy[s[j+i]]++;
            }
            if(copy==mp)    index.emplace_back(i);
        }
        return index;
  • 方法二(滑动窗口):
class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        int pLen=p.size(),sLen=s.size();
        if(pLen>sLen)   return vector<int>();
        vector<int>res;
        vector<int>sCount(26);
        vector<int>pCount(26);
        for(int i=0;i<p.size();i++){
            sCount[s[i]-'a']++;
            pCount[p[i]-'a']++;
        }
        if(sCount==pCount)   res.emplace_back(0);
        for(int i=0;i<sLen-pLen;i++){
            --sCount[s[i] - 'a'];
            ++sCount[s[i + pLen] - 'a'];
            if (sCount == pCount){
                res.emplace_back(i+1);
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值