Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- 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會越界.這個小知識點很有用