20. Valid Parentheses

来源:互联网 发布:骆驼 薛之谦 知乎 编辑:程序博客网 时间:2024/06/08 17:53

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.

根据标签显示stack,栈的特点是先入后出,后入先出,与本题的各个括号一一对应的特点相呼应。

例如'(''{''[' 左括号入栈,然后再将当前括号与stack.top()匹配,观察是否匹配,然后stack.pop(),接着匹配第二个元素,直到栈为空。

class Solution

{

public:
    bool isValid(string s) 

    {

   stack<char> st;

  int len=s.size();

            for(int i=0;i<len;i++)

                {

                    if(s[i]='('||s[i]='{'||s[i]='[')

                   st.push(s[i]);

                   else

                   if(st.empty())

                   return false;

                   else

                       {

                       char temp=st.top();

                              if((temp='('&&s[i]=')')||(temp='{'&&s[i]='}')||(temp='['&&s[i]=']'))

                             {

                                st.pop();

                              }

                             else

                            return false;

                    }

              } 

     if( st.empty())

     return true;

    else

    return  false;




}





};