LeetCode(20)-Valid Parentheses

来源:互联网 发布:去网络代理商工作好吗 编辑:程序博客网 时间:2024/06/10 23:18

问题描述:

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> stk;        int len = s.length();                for(int i = 0; i < len; i++){            if(s[i] == '[' || s[i] == '{' || s[i] == '(' ){                stk.push(s[i]);             }            else{                if(stk.empty())                     return false;                if(stk.top() == '[' && s[i] == ']')                    stk.pop();                else if(stk.top() == '{' && s[i] == '}')                    stk.pop();                else if(stk.top() == '(' && s[i] == ')')                    stk.pop();                else                    return false;            }        }        return stk.empty();    }};


0 0
原创粉丝点击