Java [leetcode 20]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.

解题思路:

Java现在不采用Stack栈了,那么我们用ArrayList替代之。

利用ArrayList来保存前括号,遇到后括号的情况就弹出ArrayList末尾数据,与之匹配。

若全部匹配,则最后是能够完全匹配的话,ArrayList应该为空。若不为空,则说明没有完全匹配。

代码如下:

public boolean isValid(String s) {
		ArrayList<Character> list = new ArrayList<Character>();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == ')' || s.charAt(i) == ']' || s.charAt(i) == '}') {
				if (list.isEmpty())
					return false;
				else {
					char tmp = list.get(list.size() - 1);
					list.remove(list.size() - 1);
					if ((s.charAt(i) == ')' && tmp != '(')
							|| (s.charAt(i) == ']' && tmp != '[')
							|| (s.charAt(i) == '}' && tmp != '{'))
						return false;
				}
			} else {
				list.add(s.charAt(i));
			}
		}
		return list.isEmpty();
	}
原文地址:https://www.cnblogs.com/zihaowang/p/4492886.html