首页 > 代码库 > LeetCode | #20 Valid Parentheses

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.

思路:

  • “([])”这样的形式也是valid,用栈,后进先出,判断规则如下:
    1. 如果是‘(‘, ‘[‘, ‘{‘,就直接入栈;
    2. 如果是‘)‘, ‘]‘, ‘}‘,就判断栈顶和该字符是不是一对,是就将栈顶pop,继续1,否则就返回false;
    3. 如果最后栈不为空,返回false,否则返回true;

可以用map也可以不用


import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class ValidParentheses {

	/*//用map存对应关系
	public boolean isValid(String s) {
		Map<Character, Character> map = new HashMap<Character, Character>(){
			{
				put(')', '(');
				put(']', '[');
				put('}', '{');
			}
		};
		Stack<String> stack = new Stack<>();
		int n = s.length();
		for(int i=0; i<n; i++){
			if(stack.empty()){
				stack.push(s.charAt(i));
				continue;
			}
			if(stack.peek() == (map.get(s.charAt(i)))){
				stack.pop();
			}else{
				stack.push(s.charAt(i));
			}
		}
		if(stack.empty())
			return true;
		return false;
    }*/
	public boolean isValid(String s) {
		
		Stack<Character> stack = new Stack<>();
		int n = s.length();
		char c;
		for(int i=0; i<n; i++){
			c = s.charAt(i);
			if(c==')' || c==']' || c=='}'){
				if(stack.empty()) return false;
				char c2 = stack.peek();
				if((c==')' && c2!='(') || (c==']' && c2!='[') || (c=='}' && c2!='{')){
					return false;
				}
				stack.pop();
			}else{
				stack.push(c);
			}
		}
		if(stack.empty())
			return true;
		return false;
    }
}


LeetCode | #20 Valid Parentheses