括号匹配精简实现代码

This commit is contained in:
游由 2022-08-03 17:27:31 +08:00
parent fdc76326f3
commit 51ddfe3c8d
1 changed files with 5 additions and 40 deletions

View File

@ -36,47 +36,12 @@ impl Solution {
/// * 👍 2979
/// * 👎 0
pub fn is_valid(s: String) -> bool {
if s.len() & 1 == 1 { return false; }
let mut v = vec![];
for c in s.chars() {
match c as char {
'(' | '[' | '{' => v.push(c),
')' => {
match v.last() {
None => return false,
Some(s) => {
if *s == '(' {
v.pop();
} else {
return false;
}
}
}
}
']' => {
match v.last() {
None => return false,
Some(s) => {
if *s == '[' {
v.pop();
} else {
return false;
}
}
}
}
'}' => {
match v.last() {
None => return false,
Some(s) => {
if *s == '{' {
v.pop();
} else {
return false;
}
}
}
}
_ => (),
for c in s.into_bytes() {
match c {
b'(' | b'[' | b'{' => v.push(c + (1 << (c & 1))),
_ => if Some(c) != v.pop() { return false }
}
}
v.is_empty()