From e839fe55e2f8c07fcfaa7c7dd1fc8d48a198fe4c Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 31 Mar 2024 11:46:39 +0800 Subject: [PATCH] 20240331 Finished --- src/problem/mod.rs | 3 +- ...preorder_serialization_of_a_binary_tree.rs | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 29f5538..8b85ce2 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -89,4 +89,5 @@ mod p2642_design_graph_with_shortest_path_calculator; mod p2580_count_ways_to_group_overlapping_ranges; mod p1997_first_day_where_you_have_been_in_all_the_rooms; mod p2908_minimum_sum_of_mountain_triplets_i; -mod p2952_minimum_number_of_coins_to_be_added; \ No newline at end of file +mod p2952_minimum_number_of_coins_to_be_added; +mod p331_verify_preorder_serialization_of_a_binary_tree; \ No newline at end of file diff --git a/src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs b/src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs new file mode 100644 index 0000000..b098284 --- /dev/null +++ b/src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs @@ -0,0 +1,51 @@ +/** + * [331] Verify Preorder Serialization of a Binary Tree + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn is_valid_serialization(preorder: String) -> bool { + let mut slots = 1; + let mut i = preorder.chars(); + + while let Some(c) = i.next() { + if slots == 0 { + return false; + } + + if (c == ',') { + continue; + } + + if (c == '#') { + slots -= 1; + } else { + while let Some(c) = i.next() { + if c == ',' { + break; + } + } + slots += 1; + } + } + + slots == 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_331() { + assert!(Solution::is_valid_serialization(String::from("9,3,4,#,#,1,#,#,2,#,6,#,#"))); + assert!(!Solution::is_valid_serialization(String::from("1,#"))); + assert!(!Solution::is_valid_serialization(String::from("9,#,#,1"))); + } +}