leetcode双指针(python与c++)

1.字符串的排列

思路:双指针+滑动窗口

python:

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        dict_={}
        for i in s1:
            dict_[i] = dict_.get(i,0)+1
        # # print('==dict_:',dict_)
        left,right =0,0
        length = 0
        minlen = float('inf')
        res = ''
        while right<len(s2):# 向右拓展
            if s2[right] in dict_:
                if dict_[s2[right]]>0:#注意要进行判断避免重复字符
                    length+=1
                dict_[s2[right]]-=1
            while length==len(s1):#包含了子串啦 这个时候左边要压缩
                if right-left+1==len(s1):#找最短的
                    return True
                left+=1
                if s2[left-1] in dict_:#注意left+1啦 所以要用left-1的字符判断是否出现在dict_中
                    dict_[s2[left - 1]] += 1
                    if dict_[s2[left-1]]>0:#避免重复字符造成的减法
                        length-=1
            right+=1
        return False

c++: 

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        map<char,int> dict_;
        for (int k=0;k<s1.size();k++)
        {
            dict_[s1[k]]++;
        }
        // map <char,int>::iterator itor = dict_.begin();        
        // //debug
        // for(;itor!=dict_.end();itor++)
        // {
        //     cout<<itor->first<<" "<<itor->second<<endl;
        // }        
        int right=0;
        int left=0;
        int remain_legth =0;
        while (right<s2.size())
        {   
            // cout<<"=dict_[s2[right]:"<<dict_[s2[right]]<<endl;
            if(dict_[s2[right]]>0)
            {
                remain_legth+=1;
            }
            dict_[s2[right]]-=1;
            while(remain_legth==s1.size())
            {
                if(right-left+1==s1.size())
                {
                    return true;
                }  
                left+=1;
                dict_[s2[left-1]]+=1;                 
                if (dict_[s2[left-1]]>0)
                {
                    remain_legth-=1;
                }
            }
            right+=1;
        }
    return false;

    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值