2022-09-17:一个字符串s,表示仓库的墙 与 货物,其中‘|‘表示墙,‘*‘表示货物。 给定一个起始下标star

2022-09-17:一个字符串s,表示仓库的墙 与 货物,其中’|’表示墙,’‘表示货物。
给定一个起始下标start和一个终止下标end,
找出子串中 被墙包裹的货物 数量。
比如:
s = “|||
“,
start = 1, end = 7,
start和end截出的子串是 “||*”,
被 ‘|’包裹的 ‘*’ 有两个,所以返回2,
现在给定一系列的start,startIndices[],和对应一系列的end ,endIndices[]。
返回每一对[start,end]的截出来的货物数量。
数据规模:
字符串s长度<=10^5,
startIndices长度 == endIndices长度 <=10^5。
亚马逊的货物和墙的问题。

答案2022-09-17:

前缀和。
时间复杂度:O(N)。
空间复杂度:O(N)。

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

fn main() {
    let s = "|**|**|*";
    let mut a = vec![0, 1, 3, 4];
    let mut b = vec![7, 7, 6, 5];
    let ans = number(s, &mut a, &mut b);
    println!("ans = {:?}", ans);
}

fn number(s: &str, starts: &mut Vec<i32>, ends: &mut Vec<i32>) -> Vec<i32> {
    let str = s.as_bytes();
    let n = str.len() as i32;
    let mut left: Vec<i32> = vec![];
    let mut right: Vec<i32> = vec![];
    let mut sum: Vec<i32> = vec![];
    for _ in 0..n {
        left.push(0);
        right.push(0);
        sum.push(0);
    }

    let mut pre = -1;
    let mut num = 0;
    for i in 0..n {
        pre = if str[i as usize] == '|' as u8 { i } else { pre };
        num += if str[i as usize] == '*' as u8 { 1 } else { 0 };
        left[i as usize] = pre;
        sum[i as usize] = num;
    }
    pre = -1;
    let mut i = n - 1;
    while i >= 0 {
        pre = if str[i as usize] == '|' as u8 { i } else { pre };
        right[i as usize] = pre;
        i -= 1;
    }

    let m = starts.len() as i32;
    let mut ans: Vec<i32> = vec![];
    for _ in 0..m {
        ans.push(0);
    }
    for i in 0..m {
        ans[i as usize] = stars(
            starts[i as usize],
            ends[i as usize],
            &mut left,
            &mut right,
            &mut sum,
        );
    }
    return ans;
}

fn stars(start: i32, end: i32, l: &mut Vec<i32>, r: &mut Vec<i32>, s: &mut Vec<i32>) -> i32 {
    let left = r[start as usize];
    let right = l[end as usize];
    if left == -1 || right == -1 || (left >= right) {
        return 0;
    }
    return if left == 0 {
        s[right as usize]
    } else {
        s[right as usize] - s[(left - 1) as usize]
    };
}

执行结果如下:

在这里插入图片描述


左神java代码

本作品采用《CC 协议》,转载必须注明作者和本文链接
微信公众号:福大大架构师每日一题。最新面试题,涉及golang,rust,mysql,redis,云原生,算法,分布式,网络,操作系统。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!