20. Valid Parentheses

来源:互联网 发布:淘宝买cpu散片哪家靠谱 编辑:程序博客网 时间:2024/05/18 04:50

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.

这种属于典型的可以用stack的实现的算法。线性扫描一遍即可。代码如下:

class Solution {public:    bool isValid(string s) {        stack<char> ref;        int len = s.size();        if (len <= 1) return false;        int i = 0;        if (s[0] == ')' || s[0] == '}' || s[0] == ']') return false;        ref.push(s[0]);        i++;        while (i < len) {            if (s[i] == '(' || s[i] == '{' || s[i] == '[') {                ref.push(s[i++]);            }            else {                if (s[i] == ')') {                    if (!ref.empty() && ref.top() == '(') ref.pop(), i++;                    else return false;                }                if (s[i] == '}') {                    if (!ref.empty() && ref.top() == '{') ref.pop(), i++;                    else return false;                }                if (s[i] == ']') {                    if (!ref.empty() && ref.top() == '[') ref.pop(), i++;                    else return false;                }            }        }        if (!ref.empty()) return false;        else return true;    }};
原创粉丝点击