Last active
September 16, 2017 03:47
-
-
Save saethlin/ab4b575eef559a095919aee18f2374a7 to your computer and use it in GitHub Desktop.
Valid Parentheses
This file contains hidden or 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
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