Valid Parentheses

有效的括号

题目

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
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:

Input: “([)]”
Output: false

Example 5:

Input: “{[]}”
Output: true

解析重点

1.这道题最重要是找出括号之间的规律,当有左括号的时候不用管,出现右括号的时候要检查左边是否有对应的括号,
有的话将其消除掉,不断重复这个过程。但是,这需要我们从内到外处理数据,我们可以借助栈来处理这种情况。
2.循环处理表达式的每个括号,当遇到左括号时,我们将其推入栈。
3.当遇到右括号时,弹出栈顶元素,看是否匹配,如果无法消除,则表达式无效,如果匹配,则消除这对数据。
4.如果最后站内任有元素,表达式无效。

java代码

具体java代码参考官方

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {

// Hash table that takes care of the mappings.
private HashMap<Character, Character> mappings;

// Initialize hash map with mappings. This simply makes the code easier to read.
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
}

public boolean isValid(String s) {

// Initialize a stack to be used in the algorithm.
Stack<Character> stack = new Stack<Character>();

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

// If the current character is a closing bracket.
if (this.mappings.containsKey(c)) {

// Get the top element of the stack. If the stack is empty, set a dummy value of '#'
char topElement = stack.empty() ? '#' : stack.pop();

// If the mapping for this bracket doesn't match the stack's top element, return false.
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
// If it was an opening bracket, push to the stack.
stack.push(c);
}
}

// If the stack still contains elements, then it is an invalid expression.
return stack.isEmpty();
}
}

undefined