From 50062fe55e8f68e94c163fd33226a4d53f66ec33 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 29 Jan 2024 14:54:25 +0800 Subject: [PATCH] 20240129 Finished --- src/problem/mod.rs | 3 +- src/problem/p514_freedom_trail.rs | 66 +++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 src/problem/p514_freedom_trail.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index c6d2d93..9a762a1 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -30,4 +30,5 @@ mod p2865_beautiful_towers_i; mod p2859_sum_of_values_at_indices_with_k_set_bits; mod p2846_minimum_edge_weight_equilibrium_queries_in_a_tree; mod p2861_maximum_number_of_alloys; -mod p365_water_and_jug_problem; \ No newline at end of file +mod p365_water_and_jug_problem; +mod p514_freedom_trail; \ No newline at end of file diff --git a/src/problem/p514_freedom_trail.rs b/src/problem/p514_freedom_trail.rs new file mode 100644 index 0000000..3732ce2 --- /dev/null +++ b/src/problem/p514_freedom_trail.rs @@ -0,0 +1,66 @@ +/** + * [514] Freedom Trail + */ +pub struct Solution {} + + +// submission codes start here + +use std::collections::HashMap; + +impl Solution { + pub fn find_rotate_steps(ring: String, key: String) -> i32 { + let mut map = HashMap::new(); + + for (index, value) in ring.chars().enumerate() { + let entry = map.entry(value).or_insert(Vec::new()); + entry.push(index); + } + + let mut dp = Vec::with_capacity(key.len()); + for _ in 0..key.len() { + dp.push(vec![i32::MAX;ring.len()]); + } + + let key: Vec = key.chars().collect(); + for (index, value) in key.iter().enumerate() { + let pos = map.get(&value).unwrap(); + + if index == 0 { + for i in pos { + dp[index][*i] = ((*i).min(ring.len() - *i) + 1) as i32; + } + } else { + for i in pos { + let last = key[index - 1]; + let last_pos = map.get(&last).unwrap(); + + for j in last_pos { + let now = *i as i32; + let last = *j as i32; + + dp[index][*i] = dp[index][*i].min( + dp[index - 1][*j] + (now - last).abs().min( + ring.len() as i32 - (now - last).abs()) + 1 + ) + } + } + } + } + + *dp[key.len() - 1].iter().min().unwrap() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_514() { + assert_eq!(Solution::find_rotate_steps("godding".to_string(), "gd".to_string()), 4); + assert_eq!(Solution::find_rotate_steps("godding".to_string(), "godding".to_string()), 13); + } +}