diff --git a/rust/20-Valid-Parentheses.rs b/rust/20-Valid-Parentheses.rs new file mode 100644 index 000000000..96e2abdcd --- /dev/null +++ b/rust/20-Valid-Parentheses.rs @@ -0,0 +1,25 @@ +use std::collections::HashMap; + +impl Solution { + pub fn is_valid(s: String) -> bool { + let mut stack: Vec = Vec::new(); + let opening = HashMap::from([(']', '['), (')', '('), ('}', '{')]); + + for c in s.chars() { + match c { + '(' => stack.push(c), + '[' => stack.push(c), + '{' => stack.push(c), + _ => { + if stack.iter().last() == opening.get(&c) { + stack.pop(); + } else { + return false; + } + } + } + } + + stack.is_empty() + } +}