' 括号检查
' 括号共有四种: 1(英文圆括号),2(中文圆括号),3[方括号],4{花括号}
' 要左右匹配(可以嵌套)
Private Shared Function isBracketsOK(strInput As String) As Boolean
' 四种括号,左右各一个,共8个
Dim brace1_open As Char = "("
Dim brace1_close As Char = ")"
Dim brace2_open As Char = "("
Dim brace2_close As Char = ")"
Dim brace3_open As Char = "["
Dim brace3_close As Char = "]"
Dim brace4_open As Char = "{"
Dim brace4_close As Char = "}"
' 四个左括号的列表
Dim list_braceOpen As List(Of Char) = New List(Of Char)
list_braceOpen.Add(brace1_open)
list_braceOpen.Add(brace2_open)
list_braceOpen.Add(brace3_open)
list_braceOpen.Add(brace4_open)
' 四个右括号的列表
Dim list_braceClose As List(Of Char) = New List(Of Char)
list_braceClose.Add(brace1_close)
list_braceClose.Add(brace2_close)
list_braceClose.Add(brace3_close)
list_braceClose.Add(brace4_close)
' 左括号 和 右括号 的一一对应关系,用字典表示
Dim dic_braces As Dictionary(Of Char, Char) = New Dictionary(Of Char, Char)
dic_braces.Add(brace1_open, brace1_close)
dic_braces.Add(brace2_open, brace2_close)
dic_braces.Add(brace3_open, brace3_close)
dic_braces.Add(brace4_open, brace4_close)
' 右括号 组成的 堆栈(先进后出)
Dim stack_close As Stack(Of Char) = New Stack(Of Char)
Dim CharArr As Char() = strInput.ToCharArray() ' 将字符串转为 字符数组
For Each _char In CharArr ' 对于每个字符
If list_braceOpen.Contains(_char) Then ' 如果这是个 左括号
stack_close.Push(dic_braces(_char)) ' 在 堆栈中 加入相应的 右括号
ElseIf list_braceClose.Contains(_char) Then ' 如果这是个 右括号
If stack_close.Count = 0 Then ' 如果 堆栈 已经空了(不能pop了)
Return False ' 报错
EndIf
Dim charPop AsChar = stack_close.Pop() ' 从 堆栈中取得一个右括号
If _char <> charPop Then ' 如果 从堆栈中取得的右括号 和 这个右括号 不同
Return False ' 报错
End If
End If
Next
If stack_close.Count > 0 Then ' 如果堆栈中还有 右括号
Return False
End If
Return True
End Function