2022-05-12:小歪每次会给你两个字符串: 笔记s1和关键词s2,请你写一个函数, 判断s2的排列之一是否是s1的子串。 如果是,返回true; 否则,返回false。 来自字节飞书团队。

答案2022-05-12:

欠债表。滑动窗口,str2存map。

代码用rust编写。代码如下:

fn main() {
    let ans=check2("fabkbbca","abcb");
    println!("ans = {}",ans);
}

fn check2( s1:&str,  s2:&str) ->bool{
    if s1.chars().count() < s2.chars().count() {
        return false;
    }

    let str2: Vec<char> = s2.chars().collect::<Vec<_>>();
     let mut count:[isize;256]=[0;256];
    for i in 0..s2.chars().count() {
        count[str2[i] as usize]+=1;
    }
    let m = s2.chars().count() as isize;
    let  st1: Vec<char> = s1.chars().collect::<Vec<_>>();
    let mut in_valid_times:isize = 0;
    let mut r:isize = 0;
    while r < m {
        if count[st1[r as usize] as usize] <= 0 {
            in_valid_times+=1;
        }
        count[st1[r as usize] as usize]-=1;
        r+=1;
    }
    while r < st1.len() as isize {
        if in_valid_times == 0 {
            return true;
        }
        if count[st1[r as usize] as usize] <= 0 {
            in_valid_times+=1;
        }
        count[st1[r as usize] as usize]-=1;
        if count[st1[(r - m) as usize] as usize] < 0 {
            in_valid_times-=1;
        }
        count[st1[(r - m) as usize] as usize]+=1;
        r+=1;
    }
    return in_valid_times == 0;
}

执行结果如下:

在这里插入图片描述


左神java代码