Skip to content

Commit fb11dce

Browse files
committed
finish algorithm7
1 parent cc54c3c commit fb11dce

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

exercises/algorithm/algorithm7.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,12 @@ impl<T> Stack<T> {
3232
}
3333
fn pop(&mut self) -> Option<T> {
3434
// TODO
35-
None
35+
let res = self.data.pop();
36+
if res.is_some()
37+
{
38+
self.size -= 1;
39+
}
40+
res
3641
}
3742
fn peek(&self) -> Option<&T> {
3843
if 0 == self.size {
@@ -102,7 +107,33 @@ impl<'a, T> Iterator for IterMut<'a, T> {
102107
fn bracket_match(bracket: &str) -> bool
103108
{
104109
//TODO
105-
true
110+
let mut stack = Stack::new();
111+
for ch in bracket.chars() {
112+
match ch {
113+
'(' | '{' | '[' => {
114+
// 左括号入栈
115+
stack.push(ch);
116+
}
117+
')' | '}' | ']' => {
118+
// 右括号:弹栈并匹配
119+
if let Some(top) = stack.pop() {
120+
if !matches!(
121+
(top, ch),
122+
('(', ')') | ('{', '}') | ('[', ']')
123+
) {
124+
return false;
125+
}
126+
}
127+
else {
128+
// 栈空却遇到右括号
129+
return false;
130+
}
131+
}
132+
_ => {} // 其他字符忽略
133+
}
134+
}
135+
// 最后栈必须为空才算全部匹配
136+
stack.is_empty()
106137
}
107138

108139
#[cfg(test)]

0 commit comments

Comments
 (0)