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

      

  • 相关阅读:
    linux 错误总结
    linux xampp常见问题
    !WebGL
    !站点列表(无关的站点)
    代码: 瀑布流
    插件:★★★ !!!图片懒加载 lazyload.js 、 jquery.scrollLoading.js
    html调用静态json例子
    !!! jquery mobile常用代码
    国内各类“壳子”浏览器,userAgent 一览
    checkbox的美化(转)
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3417602.html
Copyright © 2011-2022 走看看