-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidParentheses2.java
48 lines (43 loc) · 1.07 KB
/
ValidParentheses2.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
42
43
44
45
46
47
48
package string;
import java.util.*;
/**
* @author Shogo Akiyama
* Solved on 05/05/2020
*
* 20. Valid Parentheses
* https://leetcode.com/problems/valid-parentheses/
* Difficulty: Easy
*
* Approach: Stack
* Runtime: 1 ms, faster than 98.58% of Java online submissions for Valid Parentheses.
* Memory Usage: 37.3 MB, less than 5.06% of Java online submissions for Valid Parentheses.
*
* Time Complexity: O(n)
* Space Complexity: O(n)
* Where n is the length of the string
*
* @see StringTest#testValidParentheses()
*/
public class ValidParentheses2 {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (stack.empty()) {
return false;
} else {
char prev = stack.pop();
if (c == ')' && prev != '(') {
return false;
} else if (c == '}' && prev != '{') {
return false;
} else if (c == ']' && prev != '[') {
return false;
}
}
}
return stack.empty();
}
}