题解 | #括号序列#

括号序列

http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
//本体其实就是一个简单的栈的应用,大家不要把题目想的太复杂
    bool isValid(string s) {
        // write code here
        char stack[10000];int top=-1;
        int lenth=s.size();
        for(int i=0;i<lenth;i++)
        {
            if(top==-1)//如果栈为空那么直接入栈
            {
                stack[++top]=s[i];
            }
            else if(s[i]=='('||s[i]=='{'||s[i]=='[')//为左括号也直接入栈
            {
                stack[++top]=s[i];
            }
            else//当为右括号时需要判断此时栈顶元素是否与之对应
            {
                if(s[i]==')')
                {
                    if(top==-1||stack[top]!='(')//栈为空或者不对应则返回false,下同
                        return false;
                    else
                    {
                        top--;
                    }
                }
                else if(s[i]==']')
                {
                    if(top==-1||stack[top]!='[')
                        return false;
                    else
                    {
                        top--;
                    }
                }
                else{
                    if(top==-1||stack[top]!='{')
                        return false;
                    else top--;
                }
            }
        }
        if(top==-1)//如果最终栈空则返回true,否则返回false
            return true;
        else return false;
    }
};
全部评论

相关推荐

2 收藏 评论
分享
牛客网
牛客企业服务