diff options
author | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
---|---|---|
committer | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
commit | 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb (patch) | |
tree | 0072cca328fe5adb2ed61004010228ff85e2164d /valid-parentheses |
Diffstat (limited to 'valid-parentheses')
-rw-r--r-- | valid-parentheses/Cargo.toml | 8 | ||||
-rw-r--r-- | valid-parentheses/src/main.rs | 39 |
2 files changed, 47 insertions, 0 deletions
diff --git a/valid-parentheses/Cargo.toml b/valid-parentheses/Cargo.toml new file mode 100644 index 0000000..7b14741 --- /dev/null +++ b/valid-parentheses/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "valid-parentheses" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/valid-parentheses/src/main.rs b/valid-parentheses/src/main.rs new file mode 100644 index 0000000..5ee7e96 --- /dev/null +++ b/valid-parentheses/src/main.rs @@ -0,0 +1,39 @@ +fn main() { + let tests = vec![ + ("()", true), + ("()[]{}", true), + ("([", false) + ]; + + for test in tests { + println!("{} is {} should be {}", test.0, is_valid(test.0.to_string()).to_string(), test.1) + } +} + +fn is_valid(s: String) -> bool { + + let mut stack: Vec<char> = vec![]; + + for c in s.chars() { + match c { + '[' | '(' | '{' => stack.push(c), + ']' | ')' | '}' => { + match stack.pop() { + Some(head) => if lookup(head).unwrap() != c {return false;}, + None => return false + } + } + _ => {} + } + } + return stack.is_empty(); +} + +fn lookup(c: char) -> Option<char> { + match c { + '[' => Some(']'), + '(' => Some(')'), + '{' => Some('}'), + _ => None + } +} |