Skip to content

Latest commit

 

History

History
34 lines (27 loc) · 790 Bytes

20. Valid Parentheses.md

File metadata and controls

34 lines (27 loc) · 790 Bytes

20. Valid Parentheses

Problem

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.

tag:

  • String
  • stack

Solution

java

	public boolean isValid(String s) {
		Stack<Character> stack = new Stack<Character>();
		String left = "([{", right = ")]}";
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
				stack.push(s.charAt(i));
			} else {
				if (stack.isEmpty() || s.charAt(i) != right.charAt(left.indexOf(stack.peek())))
					return false;
				stack.pop();
			}
		}
		if (!stack.isEmpty())
			return false;
		return true;
	}