All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : May 22, 2024
Last updated : July 01, 2024
Related Topics : String, Stack
Acceptance Rate : 40.763 %
class Solution {
public boolean isValid(String s) {
Stack<Character> temp = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '[' || s.charAt(i) == '(' || s.charAt(i) == '{') {
temp.add(s.charAt(i));
} else if (s.charAt(i) == ']' || s.charAt(i) == ')' || s.charAt(i) == '}') {
if (temp.isEmpty()) {
return false;
} else {
switch (s.charAt(i)) {
case ']' :
if (temp.peek() != '[') {
return false;
}
break;
case '}' :
if (temp.peek() != '{') {
return false;
}
break;
case ')' :
if (temp.peek() != '(') {
return false;
}
break;
default :
return false;
}
temp.pop();
}
}
}
return temp.isEmpty();
}
}