zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses(stack)

    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.

     public class Solution {

    if (s == null)
    			return false;
    		Stack<Character> stack = new Stack<Character>();
    		char[] ch = s.toCharArray();
    		for (int i = 0; i < ch.length; i++) {
    			if ((ch[i] == '(') || (ch[i] == '[') || (ch[i] == '{'))
    				stack.push(ch[i]);
    			else {
    				if (stack.isEmpty())
    					return false;
    				if (ch[i] - stack.pop() > 2)
    					return false;
    			}
    		}
    		return stack.isEmpty();
    

      

        public boolean isValid(String s) {
            if (s == null)                       //改进1:可以不用String.charat(i)
    return false; //改进2: 先判断长度
    //改进三: 不需要这么多if else ,符号的判断可以用ascii码 Stack<Character> stack = new Stack<Character>(); char[] ch = s.toCharArray(); for (int i = 0; i < ch.length; i++) { if ((ch[i] == '(') || (ch[i] == '[') || (ch[i] == '{')) stack.push(ch[i]); else { if (ch[i] == ')') { if (stack.isEmpty()) return false; else if (stack.pop() != '(') return false; } if (ch[i] == ']') { if (stack.isEmpty()) return false; if (stack.pop() != '[') return false; } if (ch[i] == '}') { if (stack.isEmpty()) return false; if (stack.pop() != '{') return false; } } } if (!stack.isEmpty()) return false; else return true; } }

      

  • 相关阅读:
    播放m3u文件时不能时时更新的问题
    Oracle视图详解
    Oracle视图的作用与安全性
    Ext GridPanel 表头合并
    [AJAX] 001 AJAX核心操作
    [Java] 系统环境变量配置
    [AJAX] 002 AJAX异步验证
    判断文章/帖子操作权限
    让Tee 7.x版本和FastReport 3.x版本共存
    mysql基本语句
  • 原文地址:https://www.cnblogs.com/kydnn/p/5162915.html
Copyright © 2011-2022 走看看