本帖最后由 匿名 于 2022-2-14 16:48 编辑
答案:- fn main() {}
- fn compute_penalty(data: String, mut close_hour: i32) -> usize {
- let data_a = data.as_bytes();
- let mut res = 0;
- let mut i = 0;
- while i < data_a.len() {
- if data_a[i] != b'Y' && data_a[i] != b'N' {
- i += 1;
- continue;
- }
- if close_hour > 0 {
- if data_a[i] == b'N' {
- res += 1;
- }
- } else {
- if data_a[i] == b'Y' {
- res += 1;
- }
- }
- close_hour -= 1;
- i += 1;
- }
- res
- }
- fn find_best_closing_time(data: String) -> usize {
- let mut res = usize::MAX;
- let mut close = 0usize;
- let day: usize = data
- .chars()
- .filter(|&c| c == 'Y' || c == 'N')
- .map(|_| 1)
- .sum();
- for i in 0..=data.len() {
- let p = compute_penalty(data.clone(), i as i32);
- if res > p {
- res = p;
- close = i;
- }
- }
- close
- }
- fn get_best_closing_times_two(data: String) -> Vec<usize> {
- let mut res = vec![];
- for s in data.split("BEGIN") {
- if let Some((l, _)) = s.split_once("END") {
- let a = l.as_bytes();
- let mut i = 0;
- let mut input = "".to_owned();
- while i < a.len() {
- if a[i] == b'Y' || a[i] == b'N' {
- input.push(a[i] as char);
- }
- i += 1;
- }
- if input.len() == 0 {
- continue;
- }
- res.push(find_best_closing_time(input));
- }
- }
- res
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_one() {
- assert_eq!(compute_penalty("Y Y N Y".to_owned(), 0), 3);
- assert_eq!(compute_penalty("N Y N Y".to_owned(), 2), 2);
- assert_eq!(compute_penalty("Y Y N Y".to_owned(), 4), 1);
- }
- #[test]
- fn test_two() {
- assert_eq!(find_best_closing_time("Y Y N N".to_owned()), 2);
- assert_eq!(find_best_closing_time("Y N Y N".to_owned()), 1);
- }
- #[test]
- fn test_three() {
- assert_eq!(
- get_best_closing_times_two("BEGIN Y Y END \nBEGIN N N END".to_owned()),
- vec!(2, 0)
- );
- assert_eq!(
- get_best_closing_times_two(
- "BEGIN BEGIN \nBEGIN N N BEGIN Y Y\n END N N END".to_owned()
- ),
- vec!(2)
- );
- assert_eq!(
- get_best_closing_times_two(
- "Y Y N BEGIN Y N Y BEGIN BEGIN END Y END BEGIN Y Y N Y END BEGIN Y END Y N END"
- .to_owned()
- ),
- vec!(2, 1)
- );
- assert_eq!(
- get_best_closing_times("BEGIN BEGIN N Y Y END Y Y Y N BEGIN N N N Y END".to_owned()),
- vec!(3, 0)
- );
- }
- }
复制代码 |