• [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;
        }
    };
    

      

  • 相关阅读:
    request.setCharacterEncoding("utf-8");
    JSTL的foreach循环遍历
    EL表达式的查找范围
    Unity_图形学之_shader_学习笔记(一)
    Unity_AssetBundle笔记_(一)(俗称AB包_个人笔记欢迎指正)
    Unity C#笔记 协程详解(转)
    解决方案_And_学习链接_笔记
    Unity_一些Unity内部的重要设置
    C#_异常处理
    Unity3D_Resources封装(ResourcesManager 类)
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3417602.html
Copyright © 2020-2023  润新知