[−][src]Function leetcode_for_rust::cd0020_valid_parentheses::is_valid2
pub fn is_valid2(s: String) -> bool
Solutions
Approach 1: Stacks
-
Time complexity: O(n)
-
Space complexity: O(n)
use std::collections::HashMap; impl Solution { pub fn is_valid2(s: String) -> bool { let mut paren_stack = vec![]; let mut paren_map: HashMap<char, char> = HashMap::new(); paren_map.insert(')', '('); paren_map.insert('}', '{'); paren_map.insert(']', '['); for ch in s.chars() { match ch { '(' | '{' | '[' => paren_stack.push(ch), _ => { let expected = *paren_map.get(&ch).unwrap(); let actual = paren_stack.pop().unwrap(); if expected != actual { return false; } } } } paren_stack.is_empty() } }