-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
56 lines (54 loc) · 1.3 KB
/
Solution.java
File metadata and controls
56 lines (54 loc) · 1.3 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package Stack.easy.No_20_Valid_Parentheses;
import java.util.Stack;
/**
* FileName: Solution
* Author: EdisonLi的Windows
* Date: 2019/5/6 17:50
* Description: Valid Parentheses
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
* <p>
* An input string is valid if:
* <p>
* 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.
* <p>
* Example 1:
* <p>
* Input: "()"
* Output: true
* Example 2:
* <p>
* Input: "()[]{}"
* Output: true
* Example 3:
* <p>
* Input: "(]"
* Output: false
* Example 4:
* <p>
* Input: "([)]"
* Output: false
* Example 5:
* <p>
* Input: "{[]}"
* Output: true
* Difficulty: easy
*/
public 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.isEmpty() || stack.pop() != c){
return false;
}
}
return stack.isEmpty();
}
}