MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / par_checker3

Function par_checker3

code/chapter03/infix_to_postfix.rs:46–76  ·  view source on GitHub ↗

检测括号是否匹配

(infix: &str)

Source from the content-addressed store, hash-verified

44
45// 检测括号是否匹配
46fn par_checker3(infix: &str) -> bool {
47 let mut char_list = Vec::new();
48 for c in infix.chars() {
49 char_list.push(c);
50 }
51
52 let mut index = 0;
53 let mut balance = true;
54 let mut stack = Stack::new();
55 while index < char_list.len() && balance {
56 let c = char_list[index];
57 if '(' == c || '[' == c || '{' == c {
58 stack.push(c);
59 }
60
61 if ')' == c || ']' == c || '}' == c {
62 if stack.is_empty() {
63 balance = false;
64 } else {
65 let top = stack.pop().unwrap();
66 if !par_match(top, c) {
67 balance = false;
68 }
69 }
70 }
71
72 index += 1;
73 }
74
75 balance && stack.is_empty()
76}
77
78fn infix_to_postfix(infix: &str) -> Option<String> {
79 // 括号匹配检验

Callers 1

infix_to_postfixFunction · 0.70

Calls 5

par_matchFunction · 0.70
pushMethod · 0.45
lenMethod · 0.45
is_emptyMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected