leetcode20. Valid Parentheses

来源:互联网 发布:菜鸟网络上市 编辑:程序博客网 时间:2024/05/29 11:36

leetcode20. Valid Parentheses
思路:
做一个栈,遇到对称的符号则出栈,否则入栈,最后判断栈是否为空。

class Solution {public:    bool isValid(string s) {        string stack(s);        int top = -1;        if(s.size()<=0)            return true;        for(int i=0;i<s.size();i++){            switch(s[i]){                case '(':                case '{':                case '[':                    stack[++top] = s[i];                    break;                case ')':                    if(top<0 || stack[top]!='(') return false;                    top--;                    break;                case '}':                    if(top<0 || stack[top]!='{') return false;                    top--;                    break;                case ']':                    if(top<0 || stack[top]!='[') return false;                    top--;                    break;                default:                    return false;            }        }        if(top==-1) return true;        else return false;    }};
原创粉丝点击