LeetCode 020. Valid Parentheses

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) 
    {
        int len = s.length();
        string stack(len,' ');
        int j = -1;
        for(int i=0; i<len; i++)
        {
            //左括號,則入棧
            if(s[i]=='(' || s[i]=='[' || s[i]=='{')
            {
                j++;
                stack[j] = s[i];
            }
            //右括號,則出棧一個元素與之對比
            if(s[i]==')' || s[i]==']' || s[i]=='}')
            {
                if(j < 0) //棧爲空
                    return false;
				if((stack[j]=='('&&s[i]!=')')||(stack[j]=='['&&s[i]!=']')||(stack[j]=='{'&&s[i]!='}'))
                    return false;
                else
                    j--;
            }
        }
        if(j >= 0)  //左括號還有剩餘
            return false;
        else 
            return true;
    }
};






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