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.


    【分析】

    棧的使用,比較簡單。


    【代碼】

class Solution {
public:
    bool isValid(string s) {
        if(s.length() == 0)
            return true;
        
        stack<int> sta;
        for(int i = 0; i < s.length(); i++)
        {
            if(s[i] == '(' || s[i] == '[' || s[i] == '{')
                sta.push(s[i]);
            else if(s[i] == ')')
            {
                if(sta.empty() || sta.top() != '(')
                    return false;
                else
                    sta.pop();
            }
            else if(s[i] == ']')
            {
                if(sta.empty() || sta.top() != '[')
                    return false;
                else
                    sta.pop();
            }
            else
            {
                if(sta.empty() || sta.top() != '{')                
                    return false;
                else
                    sta.pop();
            }
        }
        
        if(sta.empty())
            return true;
        else
            return false;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章