leetcode刷题Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

 

分析题目可以发现,这里面的数据都是有一定的对称性,有一种各自匹配消除的感觉,这里就想到了, 由于{},[]和()的ASSCII码的差值还不一样,前面两个是2,后面一个是1,这个要注意一下.

这道题目的主要目的是检测测试者对栈的数据结构的熟悉程度,这道题目用栈做很方便.直接上代码

if(s.empty())
               return true;
           int num = s.size();
           int mid = int(num / 2);
           if(num%2 !=0)
               return false;
           stack <int> all;
           for(int i=0;i<num;i++)
           {

                   if(!all.empty()&&((all.top()-s[i] == -1)||(all.top()-s[i]==-2)))
                   {
                       
                          all.pop();
                   }
                   else
                   {
                       all.push(s[i]);
                   }

           }

           if(all.empty())
              return true;
           else
               return false;
    }

note:  char可以强制转换成int型

note:在运用A&& B判断时,只要A不满足条件,条件B是不执行的,所以不用担心栈的pop会越界.这个小知识点很有用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章