Valid Parentheses

Given a string 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.

Note that an empty string is also considered valid.

Example 1:

Input:
 "()"

Output:
 true

Example 2:

Input:
 "()[]{}"

Output:
 true

Example 3:

Input:
 "(]"

Output:
 false

Example 4:

Example 5:

Analysis

这种先入后出的特性很适合用栈Stack,因此利用一个stack来记录之每个字符,遍历每个字符,如果下一个字符是可以closed栈顶字符的同类括号,则出栈;最终结果就是检测这个栈是否为空

Solution

Last updated

Was this helpful?