LeetCode 20 Valid Parentheses

来源:互联网 发布:肯尼迪遇刺档案 知乎 编辑:程序博客网 时间:2024/06/15 22:11

LeetCode 20 Valid Parentheses

#include <string>#include<stack>//使用c++中的栈using namespace std;class Solution {public:    bool isValid(string s) {        stack <char> stk;//声明一个字符栈        //遍历S中的全部字符,进行出入栈操作        for (int i = 0; i < s.length(); i++){            if (s[i] == '(' || s[i] == '[' || s[i] == '{'){                stk.push(s[i]);            }            else{                if (stk.empty())                    return false;//第一个字符没能成功入栈即为不合规则的字符串,如"]"                char top = stk.top();                if ((top == '(' && s[i] == ')') || (top == '[' && s[i] == ']') || (top == '{' && s[i] == '}'))//右括号都不进栈                    stk.pop();                else                    return false;            }        }        if (stk.empty())//最后都清空的是正确的,本来就是空串的也是正确的            return true;        else            return false;//最后无法清空的为错误字符串    }};