Leetcode [Valid Parentheses]

来源:互联网 发布:ubuntu资源监视器 编辑:程序博客网 时间:2024/06/05 06:56

Problem : Valid Parentheses

Question

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) {        stack<char> p;        for(int i = 0; i < s.size(); i++) {            if(s[i] == '(' || s[i] == '{' || s[i] == '[') {                p.push(s[i]);            }            else {                if (s[i] == ')') {                    if (p.size() != 0 && p.top() == '(')                        p.pop();                    else return false;                }                if (s[i] == ']') {                    if (p.size() != 0 && p.top() == '[')                        p.pop();                    else return false;                }                if (s[i] == '}') {                    if (p.size() != 0 && p.top() == '{')                        p.pop();                    else return false;                }            }        }        if (p.size() != 0)            return false;        return true;    }};
原创粉丝点击