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.

    原题链接:https://oj.leetcode.com/problems/valid-parentheses/

    题目:给定一个仅包括'('')''{''}''[' 和 ']' 的字符串,检測输入的串是否合法。括号是否配对。

    思路:使用一个栈。遇到左括号则压入。遇到右括号则与左括号检測是否匹配,不匹配即false,弹出顶元素,循环。

    	public boolean isValid(String s){
    		int len = s.length();
    		if(len <= 1)
    			return false;
    		if(s.charAt(0) == ')' || s.charAt(0)==']' || s.charAt(0)=='}')
    			return false;
    		Stack<Character> stack = new Stack<Character>();
    		for(int i=0;i<len;i++){
    			if(s.charAt(i) == '(' || s.charAt(i)=='[' || s.charAt(i)=='{')
    				stack.push(s.charAt(i));
    			else{
    				if(stack.size() == 0)
    					return false;
    				if(s.charAt(i) == ')')
    					if(stack.peek() != '(')
    						return false;
    				if(s.charAt(i) == ']')
    					if(stack.peek() != '[')
    						return false;
    				if(s.charAt(i) == '}')
    					if(stack.peek() != '{')
    						return false;
    				stack.pop();
    			}
    		}
    		return stack.size() == 0;
    	}




  • 相关阅读:
    Mybatis的缓存
    Mybatis使用assocation和Collection实现延迟加载
    Mybatis:一对多的查询
    Mysql:事务
    Mysql:多表查询
    Mysql:数据库的设计
    Mysql:约束
    MYSQL:DQL-查询表中的记录
    panic: cannot create context from nil parent
    $request input 获取参数null
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/6984670.html
Copyright © 2011-2022 走看看