每日一题 21.02.10 LeetCode 567. 字符串的排列 java题解

题目

https://leetcode-cn.com/problems/permutation-in-string/
在这里插入图片描述

分析

思路是 s2的字串和s1拥有相同的字符种类和次数。
winCount,表示滑动窗口在 s2 上滑动的时候,出现在 s1 中的字符的种类数。

代码

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int len1=s1.length();
        int len2=s2.length();
        char[] p=s1.toCharArray();
        char[] t=s2.toCharArray();
        int[] pf=new int[26];
        int[] tf=new int[26];
        int p_count=0;
        //统计s1中字符出现次数
        for(char c:p){
            pf[c-'a']++;
        }
        //统计s1中字符种类数
        for(int i=0;i<26;i++){
            if(pf[i]>0)
                p_count++;
        }
        int left=0;
        int right=0;
        int winCount=0;//s2中满足条件的字符种类数
        while(right<len2){
        	//s1中存在的字符
            if(pf[t[right]-'a']>0){
            	//s2中此字符次数+1
                tf[t[right]-'a']++;
                //字符出现次数相等
                if(pf[t[right]-'a']==tf[t[right]-'a']){
                    winCount++;
                }
            }
            right++;
            //s2子串中种类数=s1中种类数
            while(winCount==p_count){
            	//s2字串长度=s1字串长度,找到了
                if(right-left==len1){
                    return true;
                }
                //左指针右移
                if(pf[t[left]-'a']>0){
                    tf[t[left]-'a']--;
                    if(tf[t[left]-'a']<pf[t[left]-'a'])
                        winCount--;
                }
                left++;
            }
        }
        return false;
    }
}

复杂度

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值