[rust] [leetcode] valid-parentheses
阿新 • • 發佈:2018-12-27
// 近日閒暇練練 Rust 興許以後寫分散式系統的時候會和它打交道呢
use std::collections::HashMap; impl Solution { pub fn is_valid(s: String) -> bool { let pairs: HashMap<char, char> = [ ('(', ')'), ('[', ']'), ('{', '}'), ].iter().cloned().collect(); let mut stack: Vec<char> = vec![]; for c in s.chars() { if pairs.contains_key(&c) { stack.push(c) } else if stack.pop().and_then(|k| pairs.get(&k)).unwrap_or(&'#') != &c { return false; } } stack.is_empty() } }