-
Notifications
You must be signed in to change notification settings - Fork 531
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
First working example. Not a good example, but the tests pass
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<char>, | ||
} | ||
|
||
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::<Vec<_>>(), | ||
} | ||
} | ||
|
||
pub fn are_balanced(&self) -> bool { | ||
let mut matches: Vec<char> = 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] { | ||
['{', '[', '(', ')', ']', '}'] | ||
} | ||
} |