Valid Parentheses

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;
    }
};
發佈了19 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章