From 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb Mon Sep 17 00:00:00 2001 From: Orangerot Date: Thu, 27 Jun 2024 11:30:16 +0200 Subject: Initial commit --- valid-parentheses/src/main.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 valid-parentheses/src/main.rs (limited to 'valid-parentheses/src') diff --git a/valid-parentheses/src/main.rs b/valid-parentheses/src/main.rs new file mode 100644 index 0000000..5ee7e96 --- /dev/null +++ b/valid-parentheses/src/main.rs @@ -0,0 +1,39 @@ +fn main() { + let tests = vec![ + ("()", true), + ("()[]{}", true), + ("([", false) + ]; + + for test in tests { + println!("{} is {} should be {}", test.0, is_valid(test.0.to_string()).to_string(), test.1) + } +} + +fn is_valid(s: String) -> bool { + + let mut stack: Vec = vec![]; + + for c in s.chars() { + match c { + '[' | '(' | '{' => stack.push(c), + ']' | ')' | '}' => { + match stack.pop() { + Some(head) => if lookup(head).unwrap() != c {return false;}, + None => return false + } + } + _ => {} + } + } + return stack.is_empty(); +} + +fn lookup(c: char) -> Option { + match c { + '[' => Some(']'), + '(' => Some(')'), + '{' => Some('}'), + _ => None + } +} -- cgit v1.2.3