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.

分析:字符串符号配对。采用栈的后进先出特点就可解决。

        利用一个栈来保存前括号,然后有后括号来时弹出栈顶来判断。

public class Solution {
    public boolean isValid(String s) {
		Stack<Character> st = new Stack<Character>();
		
		for(int i=0; i<s.length(); i++) {
			char temp = s.charAt(i);
			if(temp == '[' || temp == '{' || temp == '(') {
				st.add(temp);
			} else {
				if(st.empty()) {
					return false;
				}
				char c = st.peek();
				if((temp == ']' && c == '[') || (temp == '}' && c == '{') || (temp == ')' && c == '(')) {
					st.pop();
				}else {
					return false;
				}
			}
		}
		return st.empty();
	}
原文地址:https://www.cnblogs.com/zywu/p/5496218.html