码迷,mamicode.com
首页 > 其他好文 > 详细

20. Valid Parentheses(stack)

时间:2016-01-27 14:30:10      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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

  

20. Valid Parentheses(stack)

标签:

原文地址:http://www.cnblogs.com/kydnn/p/5162915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!