Here, We see Valid Parentheses problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Valid Parentheses LeetCode Solution
Problem Statement ->
Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false
Valid Parentheses Leetcode Solution C++ ->
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char c : s){
if(c == '('|| c == '{' || c == '['){
st.push(c);
}else{
if(st.empty()) return false;
if(c == ')' && st.top() != '(') return false;
if(c == '}' && st.top() != '{') return false;
if(c == ']' && st.top() != '[') return false;
st.pop();
}
}
return st.empty();
}
};
Code language: C++ (cpp)
Valid Parentheses Leetcode Solution Java ->
class Solution {
public boolean isValid(String s) {
HashMap map = new HashMap();
map.put('(',')');
map.put('[',']');
map.put('{','}');
Stack<Character> stack = new Stack<>();
for(int i = 0;i < s.length();i++){
char c = s.charAt(i);
if(c == '(' || c == '{' || c == '['){
stack.push(c);
}else{
if(stack.isEmpty()){
return false;
}
if(map.get(stack.pop()).equals(c)){
continue;
}else{
return false;
}
}
}
return stack.isEmpty();
}
}
Code language: Java (java)
Valid Parentheses Leetcode Solution JavaScript ->
var isValid = function(s) {
const stack = [];
for (let i = 0 ; i < s.length ; i++) {
let c = s.charAt(i);
switch(c) {
case '(': stack.push(')');
break;
case '[': stack.push(']');
break;
case '{': stack.push('}');
break;
default:
if (c !== stack.pop()) {
return false;
}
}
}
return stack.length === 0;
};
Code language: JavaScript (javascript)
Valid Parentheses Leetcode Solution Python ->
class Solution(object):
def isValid(self, s):
opcl = dict(('()', '[]', '{}'))
stack = []
for idx in s:
if idx in '([{':
stack.append(idx)
elif len(stack) == 0 or idx != opcl[stack.pop()]:
return False
return len(stack) == 0
Code language: Python (python)