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.
題意
判斷所給字符串是否符合規則,即括號的配對。
題解
用棧的特性可以很方便解決這個問題,遍歷到左邊的括號則入棧,遍歷到右邊的則把棧頂的元素拿來對比,然後再出棧。
左右匹配有兩個方法 一個是用"([{" 與")]}",左邊括號的下標與右邊括號的下標一樣 即stk.top () == left[right.find (c)]來判斷
還有一個辦法是用ascii碼 注意其中兩個左括號+1爲其右括號 但有一個的左括號+2纔是其右括號。這個做法可能會有點不嚴謹,但在輸入保證是隻有括號的情況下還是沒問題的。
class Solution {
public:
bool isValid(string s) {
stack<char> left;
for(int i=0;i!=s.size();i++)
{
if(s[i]==')'||s[i]==']'||s[i]=='}')
{
if(left.empty())
return false;
else if(s[i]!=left.top()+1&&s[i]!=left.top()+2)
return false;
else left.pop();
}
else left.push(s[i]);
}
if(left.empty())
return true;
return false;
}
};