diff --git a/exercises/bracket-push/example.rs b/exercises/bracket-push/example.rs index 8b1378917..0ca647cc0 100644 --- a/exercises/bracket-push/example.rs +++ b/exercises/bracket-push/example.rs @@ -1 +1,49 @@ +// The code below is a stub. Just enough to satisfy the compiler. +// In order to pass the tests you can add-to or change any of this code. +pub struct Brackets { + brackets: Vec, +} + +impl<'a> From<&'a str> for Brackets { + fn from(i: &str) -> Self { + Brackets::new(String::from(i)) + } +} + +impl Brackets { + pub fn new(s: String) -> Self { + Brackets { + brackets: s.chars().filter(|c| Brackets::brackets().contains(c)).collect::>(), + } + } + + pub fn are_balanced(&self) -> bool { + let mut matches: Vec = Vec::new(); + + for b in self.brackets.clone() { + if matches.is_empty() { + matches.push(b); + } else { + let t = (matches.pop().unwrap(), b); + let m = match t { + ('[', ']') => true, + ('{', '}') => true, + ('(', ')') => true, + _ => false, + }; + + if !m { + matches.push(t.0); + matches.push(t.1); + } + } + } + + matches.is_empty() + } + + fn brackets() -> [char; 6] { + ['{', '[', '(', ')', ']', '}'] + } +}