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/

    思路1:经典的栈匹配。一个栈,左符号入栈,右符号出栈。最后检查栈是否为空。

    public class Solution {
    	public boolean isValid(String s) {
    		if (s == null || s.length() == 0)
    			return true;
    		Stack<Character> stack = new Stack<Character>();
    		int n = s.length();
    		for (int i = 0; i < n; i++) {
    			char ch = s.charAt(i);
    			if (ch == '(' || ch == '{' || ch == '[')
    				stack.push(ch);
    			else {
    				if (stack.isEmpty())
    					return false;
    				char out = stack.pop();
    				if (ch == ')' && out != '(' || ch == '}' && out != '{'
    						|| ch == ']' && out != '[')
    					return false;
    			}
    
    		}
    		if (!stack.isEmpty())
    			return false;
    		return true;
    	}
    
    	public static void main(String[] args) {
    		// true
    		System.out.println(new Solution().isValid("()"));
    
    		// true
    		System.out.println(new Solution().isValid("()[]{}"));
    
    		// false
    		System.out.println(new Solution().isValid("(]"));
    
    		// false
    		System.out.println(new Solution().isValid("([)]"));
    
    	}
    
    }

    第二遍记录:

      算法不变,注意栈空判断。 

  • 相关阅读:
    HTML5:超文本标记语言
    Redis持久化
    ACID VS BASE+CAP
    Redis
    NoSQL(Redis、Menchche、MongoDB)
    transient关键字
    Struts2声明式验证相关问题
    struts2国际化相关问题
    Struts2
    SSH整合的详细步骤
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810700.html
Copyright © 2011-2022 走看看