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]
};
}
评论