MCPcopy Index your code
hub / github.com/neetcode-gh/leetcode / isValid

Method isValid

java/0020-valid-parentheses.java:3–21  ·  view source on GitHub ↗
(String s)

Source from the content-addressed store, hash-verified

1class Solution {
2
3 public boolean isValid(String s) {
4 if (s.length() % 2 != 0) return false;
5 Stack<Character> stack = new Stack<>();
6 for (int i = 0; i < s.length(); i++) {
7 if (
8 stack.isEmpty() &&
9 (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']')
10 ) return false; else {
11 if (
12 s.charAt(i) == ')' && stack.peek() == '('
13 ) stack.pop(); else if (
14 s.charAt(i) == '}' && stack.peek() == '{'
15 ) stack.pop(); else if (
16 s.charAt(i) == ']' && stack.peek() == '['
17 ) stack.pop(); else stack.add(s.charAt(i));
18 }
19 }
20 return stack.isEmpty();
21 }
22}
23
24//Solution with HashMap Lookup table as described in the video

Callers

nothing calls this directly

Calls 8

equalsMethod · 0.80
isEmptyMethod · 0.45
peekMethod · 0.45
popMethod · 0.45
addMethod · 0.45
putMethod · 0.45
getMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected