using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValidParentheses { // 如果不存在星号,我们甚至连stack都可以不用,直接用一个变量,遇到左括号,自增1,遇到右括号,如果变量为0,直接返回false,否则自减1 //最后只要看变量是否为0即可。 class Program { public class Node { public string val; public Node Next; public Node(string s) { val = s; } } public class Stack { public Node Top; public void PushIn(Node nd) { if (Top != null) { Node temp = Top; Top = nd; Top.Next = temp; } else { Top = nd; Top.Next = null; } } public Node PopOut() { Node nd = null; if (Top != null) { nd.val = Top.val; Top = Top.Next; } return nd; } } public static void Match(string s, ref Stack A, ref Stack B) { //取元素,如果是左括号压入栈A中。如果是右括号,将元素放入栈B中,直到取到与之匹配的左括号,如果A空之后,右括号还没有找到,将AB互换。但是找到了,将B的元素压入A中。 if (s == "(" || s == "[" || s == "{") { A.PushIn(new Node(s)); } else if (s == ")" || s == "]" || s == "}") { while (A.Top != null) { Node temp = A.PopOut(); if (temp.val == "(" && s == ")" || temp.val == "[" && s == "]" || temp.val == "{" && s == "}") { s = string.Empty; break; } else { B.PushIn(temp); } } if (s != string.Empty) { B.PushIn(new Node(s)); } if (A.Top == null) { Stack st = A; A = B; B = st; } else { while (B.Top != null) { A.PushIn(B.PopOut()); } } } } static void Main(string[] args) { string[] slist = { "a","(","[","+","}",")","]"}; Stack A = new Stack(); Stack B = new Stack(); for (int i = 0; i < slist.Length; i++) { Match(slist[i],ref A,ref B); } while (A.Top != null) { Console.Write(A.Top.val+" "); A.Top = A.Top.Next; } Console.ReadKey(); } } }