1、Valid Parentheses 括號的匹配
題目:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
思路:
1、設計一個堆棧stack,將’(‘, ‘{‘, ‘[‘放進去;
2、如果爲 ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’,則判斷堆棧頂端是否爲相對應的括號形式,如果不對應,則爲false;
3、如果最後堆棧爲空,則表示全都匹配過了,返回爲真;
代碼:
class Solution {
public:
bool isValid(string s) {
stack<char> charstack;
for(int i=0;i<s.length();i++)
{
char charParenthes=s[i];
if(charParenthes!=')' && charParenthes!='}' && charParenthes!=']')
charstack.push(charParenthes);
else
{
if(charstack.size()==0) return false;
char top=charstack.top();
switch(charParenthes)
{
case ')':
if(top=='(') charstack.pop();
else
return false;
break;
case '}':
if(top=='{') charstack.pop();
else
return false;
break;
case ']':
if(top=='[') charstack.pop();
else
return false;
break;
}
}
}
if(charstack.size()==0) return true;
else return false;
}
};