Skip to content

Latest commit

 

History

History
79 lines (61 loc) · 1.43 KB

File metadata and controls

79 lines (61 loc) · 1.43 KB

20. Valid Parentheses

Description

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.ta#### Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

Solution

  • java
/*
  Success Details:
  Runtime: 1 ms, faster than 99.15% of Java online submissions for Valid Parentheses.
  Memory Usage: 36.4 MB, less than 86.39% of Java online submissions for Valid Parentheses.       
 */
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(')');
            } else if (c == '[') {
                stack.push(']');
            } else if (c == '{') {
                stack.push('}');
            } else {
                if (stack.empty() || c != stack.pop()) {
                    return false;
                }
            }
        }
        return stack.empty();
    }
}