首页 » 编程之美 » 正文

[leetcode_20]Valid Parentheses

给定一个字符串,里面只有(){}[]这六种字符,判断,是否它们能够匹配。
栈即可解决该问题。

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

发表评论