20. Valid Parentheses #Stack (Easy)

Problem:###

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.

Solution:###

Very classic stack problem.
If meet any left parentheses, push it into stack.
If meet any right parentheses, check whether the top of the stack is the proper left parentheses. If valid, pop it. If not valid, return false.
Finally check whether the stack is empty. If it's not empty, then it's also invalid.

class Solution {
public:
    bool isValid(string s) {
        bool result = true;
        if(s.size() == 0) return true;
        stack<char> p;
        for(int i = 0;i < s.size();i++)
        {
            if(s[i] == '(' || s[i] == '[' || s[i] == '{')
                p.push(s[i]);
            else
            {
                if (p.empty()) 
                    return false;
                if (s[i] == ')' && p.top() == '(') p.pop();
                else if (s[i] == ']' && p.top() == '[') p.pop();
                else if (s[i] == '}' && p.top() == '{') p.pop();
                else
                    return false;
            }
        }
        if (!p.empty()) //important!!!!!!!
            return false;
        return result;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,089評(píng)論 0 23
  • 覺得聲音比以前好聽點(diǎn)啦 優(yōu)點(diǎn): 1.快準(zhǔn),有點(diǎn)找到感覺 2.互動(dòng)感變強(qiáng) 3.講的比較細(xì) 缺點(diǎn): 1.儀式感太強(qiáng),親...
    cindy蕾蕾閱讀 206評(píng)論 0 0
  • 今天和先生、Peter、業(yè)務(wù)員聊了下關(guān)于線上的事情,啟發(fā)很多,之前一心追求的東西現(xiàn)在看來還不是時(shí)機(jī),只有腳踏實(shí)地一...
    王德彪閱讀 192評(píng)論 0 0
  • 存儲(chǔ)屬性計(jì)算屬性屬性觀察器類型屬性 存儲(chǔ)屬性 存儲(chǔ)常量或變量作為實(shí)例的一部分,用于類和結(jié)構(gòu)體。 栗子 等下!?? 先...
    HunterDude閱讀 554評(píng)論 0 4
  • 文/諶基平 類似像我這種帶點(diǎn)某個(gè)領(lǐng)域的“專家”性質(zhì)的人,經(jīng)常在微信上遇到這樣的場(chǎng)景 請(qǐng)問新媒體營銷怎么做? 請(qǐng)問小...
    諶基平閱讀 842評(píng)論 0 0

友情鏈接更多精彩內(nèi)容