zoukankan      html  css  js  c++  java
  • [LeetCode]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.

    思考:{ [ ( 入栈,) ] } 出栈匹配。

    class Solution {
    public:
        bool isValid(string s) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int len=s.size();
    		int i;
    		bool ans=true;
    		stack<char> p;
    		char temp;
    		for(i=0;i<len;i++)
    		{
    			if(s[i]=='('||s[i]=='['||s[i]=='{')
    				p.push(s[i]);
    			else if(s[i]==')')
    			{
    				if(p.empty()) return false;
    				else
    				{
    					temp=p.top();
    					if(temp!='(') return false;
    					p.pop();
    				}
    			}
    			else if(s[i]==']')
    			{
    				if(p.empty()) return false;
    				else
    				{
    					temp=p.top();
    					if(temp!='[') return false;
    					p.pop();
    				}
    			}
    			else if(s[i]=='}')
    			{
    				if(p.empty()) return false;
    				else
    				{
    					temp=p.top();
    					if(temp!='{') return false;
    					p.pop();
    				}
    			}
    		}
    		if(p.size()>0) return false;
    		return ans;
        }
    };
    

    2014-03-27 16:13:30

    class Solution {
    public:
        bool isValid(string s) {
            int len=s.size();
            if(len==0) return true;
            stack<char> temp;
            int i=0;
            char ch;
            while(i<len)
            {
                if(s[i]=='('||s[i]=='['||s[i]=='{') temp.push(s[i]);
                else
                {
                    if(temp.empty()) return false;
                    ch=temp.top();
                    if(s[i]==')'&&ch!='(') return false;
                    if(s[i]==']'&&ch!='[') return false;
                    if(s[i]=='}'&&ch!='{') return false;
                    temp.pop();
                }
                i++;
            }
            if(!temp.empty()) return false;
            else return true;
        }
    };
    

      

  • 相关阅读:
    C语言第十一周作业
    C语言第十周作业
    C语言第九周编程作业
    C语言第八周编程作业
    C语言第七周作业
    第六周作业
    第五周作业
    第四周作业
    第三周作业
    【BZOJ1488】[HNOI2009]图的同构计数
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3417602.html
Copyright © 2011-2022 走看看