Valid Parentheses

题目描述

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. 

Solution:

典型的栈应用,用栈解决,复杂度O(n)

题目大意:

给一串只包含有 '('')''{''}''[' 和']' ,的字符串,要求判定是否是合法的。

实现代码:

                  class Solution {
public:
    bool isValid(string s) {
        int top=-1,index=0,length=s.size();  
        char* stack=(char*)malloc(sizeof(char)*length);  
        //stack<char> stack;
        while(index<length)
        {  
            if(s[index]==')')
            {  
                if(top>=0 && stack[top]=='(')top--;  //弹出
                else return false;  
            }
            else if(s[index]=='}')
            {  
                if(top>=0 && stack[top]=='{')top--;  
                else return false;  
            }else if(s[index]==']')
            {  
                if(top>=0 && stack[top]=='[')top--;  
                else return false;  
            }else stack[++top]=s[index];  
            index++;  
        }  
        return top==-1;  
    }
};


代码2:

       class Solution {
public:
    bool isValid(string s) {
        int index=0,length=s.size();  
        stack<char> st;
        while(index<length)
        {  
            if(s[index]==')')
            {  
                if(!st.empty() && st.top()=='(') st.pop();  //弹出
                else return false;  
            }
            else if(s[index]=='}')
            {  
                if(!st.empty() && st.top()=='{') st.pop();  //弹出  
                else return false;  
            }
            else if(s[index]==']')
            {  
                if(!st.empty() && st.top()=='[') st.pop();  //弹出 
                else return false;  
            }
            else 
                st.push(s[index]);  
            index++;  
        }  
            return st.empty(); //成对出现,最后栈一定为空;
    }
};



版权声明:本文为weixin_40039738原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。