Skip to content

Commit

Permalink
-- brackets full
Browse files Browse the repository at this point in the history
  • Loading branch information
djnzx committed Oct 29, 2024
1 parent 343c3ed commit fc10a44
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 3 deletions.
Binary file added src/practice/p13/brackets_full.pdf
Binary file not shown.
86 changes: 83 additions & 3 deletions src/practice/p13/brackets_full.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,87 @@
use std::collections::{HashMap, HashSet};

/// straightforward
fn brackets_is_valid_full0(s: String) -> bool {
let mut stack = Vec::new();

for c in s.chars() {
match c {
'{' => stack.push(c),
'(' => stack.push(c),
'[' => stack.push(c),
'<' => stack.push(c),
'}' => match stack.pop() {
None => return false,
Some(top) => {
if top != '{' {
return false;
}
}
},
')' => match stack.pop() {
None => return false,
Some(top) => {
if top != '(' {
return false;
}
}
},
']' => match stack.pop() {
None => return false,
Some(top) => {
if top != '[' {
return false;
}
}
},
'>' => match stack.pop() {
None => return false,
Some(top) => {
if top != '<' {
return false;
}
}
},
_ => {}
}
}

stack.is_empty()
}

fn brackets_is_valid_full1(s: String) -> bool {
let open = HashSet::<char>::from_iter("{[(<".chars());
let mut stack = Vec::new();

fn matches(op: char, cur: char) -> bool {
match (op, cur) {
('<', '>') => true,
('[', ']') => true,
('(', ')') => true,
('{', '}') => true,
_ => false,
}
}

for c in s.chars() {
match c {
c if open.contains(&c) => stack.push(c),
c => match stack.pop() {
None => return false,
Some(x) => {
if !matches(x, c) {
return false;
}
}
},
_ => {}
}
}

stack.is_empty()
}

/// straightforward
fn brackets_is_valid_full2(s: String) -> bool {
let pairs = HashMap::from([('}', '{'), (')', '('), (']', '['), ('>', '<')]);
let open = HashSet::<char>::from_iter("{[(<".chars());
let close = HashSet::<char>::from_iter("}])>".chars());
Expand All @@ -24,7 +104,7 @@ fn brackets_is_valid_full1(s: String) -> bool {
stack.is_empty()
}

fn brackets_is_valid_full2(s: String) -> bool {
fn brackets_is_valid_full3(s: String) -> bool {
let open = HashSet::<char>::from_iter("{[(<".chars());
let pairs = HashMap::from([('}', '{'), (')', '('), (']', '['), ('>', '<')]);

Expand All @@ -50,7 +130,7 @@ fn brackets_is_valid_full2(s: String) -> bool {
}

/// more functional
fn brackets_is_valid_full3(s: String) -> bool {
fn brackets_is_valid_full4(s: String) -> bool {
let pairs = HashMap::from([('}', '{'), (')', '('), (']', '['), ('>', '<')]);
let open = HashSet::<char>::from_iter("{[(<".chars());
let close = HashSet::<char>::from_iter("}])>".chars());
Expand Down

0 comments on commit fc10a44

Please sign in to comment.