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;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,891評論 0 23
  • 覺得聲音比以前好聽點啦 優點: 1.快準,有點找到感覺 2.互動感變強 3.講的比較細 缺點: 1.儀式感太強,親...
    cindy蕾蕾閱讀 178評論 0 0
  • 今天和先生、Peter、業務員聊了下關于線上的事情,啟發很多,之前一心追求的東西現在看來還不是時機,只有腳踏實地一...
    王德彪閱讀 162評論 0 0
  • 存儲屬性計算屬性屬性觀察器類型屬性 存儲屬性 存儲常量或變量作為實例的一部分,用于類和結構體。 栗子 等下!?? 先...
    HunterDude閱讀 524評論 0 4
  • 文/諶基平 類似像我這種帶點某個領域的“專家”性質的人,經常在微信上遇到這樣的場景 請問新媒體營銷怎么做? 請問小...
    諶基平閱讀 796評論 0 0