Skip to content

Instantly share code, notes, and snippets.

@saethlin
Last active September 16, 2017 03:47
Show Gist options
  • Save saethlin/ab4b575eef559a095919aee18f2374a7 to your computer and use it in GitHub Desktop.
Save saethlin/ab4b575eef559a095919aee18f2374a7 to your computer and use it in GitHub Desktop.
Valid Parentheses
pub struct Solution {}
impl Solution {
pub fn is_valid(s: &str) -> bool {
let mut num_open_seen = 0;
for (i, c) in s.chars().enumerate() {
let maybe_last_open = s.split_at(i)
.0
.chars()
.rev()
.filter(|c| match c {
&'{' | &'[' | &'(' => true,
_ => false,
})
.skip(num_open_seen)
.next();
match c {
'}' => {
match maybe_last_open {
Some(last_open) => {
if last_open != '{' {
return false;
}
}
None => {
return false;
}
}
num_open_seen += 1;
}
']' => {
match maybe_last_open {
Some(last_open) => {
if last_open != '[' {
return false;
}
}
None => {
return false;
}
}
num_open_seen += 1;
}
')' => {
match maybe_last_open {
Some(last_open) => {
if last_open != '(' {
return false;
}
}
None => {
return false;
}
}
num_open_seen += 1;
}
// You might think we push onto a stack here
_ => {}
}
}
return true;
}
}
fn main() {
println!("{}", Solution::is_valid("(){}"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment