1
class Solution {
2
public boolean isValid(String s) {
3
Stack<Character> stack = new Stack<Character>(); // create an empty stack
4
for (char c : s.toCharArray()) { // loop through each character in the string
5
if (c == '(') // if the character is an opening parenthesis
6
stack.push(')'); // push the corresponding closing parenthesis onto the stack
7
else if (c == '{') // if the character is an opening brace
8
stack.push('}'); // push the corresponding closing brace onto the stack
9
else if (c == '[') // if the character is an opening bracket
10
stack.push(']'); // push the corresponding closing bracket onto the stack
11
else if (stack.isEmpty() || stack.pop() != c) // if the character is a closing bracket
12
// if the stack is empty (i.e., there is no matching opening bracket) or the top of the
13
// stack
14
// does not match the closing bracket, the string is not valid, so return false
15
return false;
16
}
17
// if the stack is empty, all opening brackets have been matched with their corresponding
18
// closing brackets,
19
// so the string is valid, otherwise, there are unmatched opening brackets, so return false
20
return stack.isEmpty();
21
}
22
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0