020.Valid Parentheses

Solution 1: accepted

This is an easy one.

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
public class Solution {
public boolean isValid(String s) {
Stack cache = new Stack();
for (int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if (current == '(' || current == '[' || current == '{')
cache.push(current + "");
if (current == ')')
if (!cache.isEmpty() && cache.peek().equals("("))
cache.pop();
else
return false;
if (current == ']')
if (!cache.isEmpty() && cache.peek().equals("["))
cache.pop();
else
return false;
if (current == '}')
if (!cache.isEmpty() && cache.peek().equals("{"))
cache.pop();
else
return false;
}
return cache.isEmpty();
}
}