c # stack to achieve effective use of parentheses

demand:

Includes only a given  '(', ')', '{', '}', '[', ']' string, it determines whether the string is valid.

Valid string must meet:

  1. Left bracket must be closed by a closing parenthesis of the same type.
  2. Left parenthesis must be closed in the correct order.

Note the empty string can be considered a valid string.

code show as below:

       public static bool IsValiad(string s)
       {
           Stack<string> stack = new Stack<string>();//创建一个字符串的栈
           Dictionary<string, string> dic = new Dictionary<string, string>();
           dic.Add("(", ")");
           dic.Add("[", "]");
           dic.Add("{", "}");
           if (string.IsNullOrEmpty(s)) return true;
           for (int i = 0; i < s.Length; i++)
           {
               if (s[i] == '(' || s[i] == '[' || s[i] == '{')
               {
                   stack.Push(s[i].ToString());  
               }
               else {
                     if (stack.Count == 0) return false;
                       string sign = stack.Pop();
                       if (dic[sign] != s[i].ToString()) return false;
                    
               }
           }
           return stack.Count == 0 ? true : false;
       }

Code analysis:

              1. encountered parentheses to the left when the left brackets onto the stack

              2. encountered element to the right top of the stack are put in brackets pop, and then determine whether the current equivalent of the right bracket and the top element corresponding right parenthesis

             3. extreme cases, if the characters are all left or all right-symbol symbol. Both cases may be determined by determining whether any element of the stack, the correct string data stack pop will be

Guess you like

Origin www.cnblogs.com/97310ZT/p/10972671.html