20. Valid Parentheses
/**
* Problem: LeetCode 20 - Valid Parentheses
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public boolean isValid(String s) {
if ((s.length() & 1) == 1) return false;
char[] stack = new char[s.length()];
int top = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
stack[++top] = c;
} else {
if (top < 0) return false;
char open = stack[top--];
if ((c == ')' && open != '(') ||
(c == '}' && open != '{') ||
(c == ']' && open != '[')) {
return false;
}
}
}
return top == -1;
}
}
"""
Problem: LeetCode 20 - Valid Parentheses
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
stack = []
matching = {')': '(', '}': '{', ']': '['}
for c in s:
if c in "({[":
stack.append(c)
else:
if not stack or stack.pop() != matching[c]:
return False
return len(stack) == 0
/**
* Problem: LeetCode 20 - Valid Parentheses
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
using namespace std;
/**
* Problem: LeetCode 20 - Valid Parentheses
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
bool isValid(string s) {
if (s.length() % 2 != 0) return false;
vector<char> stack(s.length());
int top = -1;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
stack[++top] = c;
} else {
if (top < 0) return false;
char open = stack[top--];
if ((c == ')' && open != '(') ||
(c == '}' && open != '{') ||
(c == ']' && open != '[')) {
return false;
}
}
}
return top == -1;
}
};
/**
* Problem: LeetCode 20 - Valid Parentheses
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
var isValid = function(s) {
if ((s.length & 1) === 1) return false;
const stack = [];
const map = { ')': '(', '}': '{', ']': '[' };
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c === '(' || c === '{' || c === '[') {
stack.push(c);
} else {
if (stack.length === 0 || stack.pop() !== map[c]) {
return false;
}
}
}
return stack.length === 0;
};