Valid Parentheses_LeetCode

Description:

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.

 

解题思路:

详细参见之前博客

http://www.cnblogs.com/SYSU-Bango/p/6306962.html

 

代码:

class Solution {
public:
    bool isValid(string str) {
        int count = 0;
        int size = str.length();
        stack<char> temp;
        for (int i = 0; i < size; i++) {
            if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
                temp.push(str[i]);
            } else {
                if (str[i] == ')') {
                    if (!temp.empty() && temp.top() == '(') {
                        temp.pop();
                    } else {
                        //cout << "No" << endl;
                        return false;
                        count = 1;
                        break;
                    }
                }
                if (str[i] == '}') {
                    if (!temp.empty() && temp.top() == '{') {
                        temp.pop();
                    } else {
                        //cout << "No" << endl;
                        return false;
                        count = 1;
                        break;
                    }
                }
                if (str[i] == ']') {
                    if (!temp.empty() && temp.top() == '[') {
                        temp.pop();
                    } else {
                        //cout << "No" << endl;
                        return false;
                        count = 1;
                        break;
                    }
                }
            }
        }
        if (count == 0) {
            if (temp.empty() == true) {
            //cout << "Yes" << endl; 
                return true;
        } else {
        //cout << "No" << endl;
                return false;
    }
        }
    }
};


        
        

 

posted @ 2017-10-16 11:58  SYSU_Bango  阅读(134)  评论(0)    收藏  举报