Last updated on October 10th, 2024 at 01:59 am
Here, We see Valid Parentheses LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.
List of all LeetCode Solution
Topics
Stack, String
Companies
Airbnb, Amazon, Bloomberg, Facebook, Google, Microsoft, Twitter, Zenefits
Level of Question
Easy
Valid Parentheses LeetCode Solution
Table of Contents
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
1. 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(); } };
2. 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(); } }
3. 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; };
4. 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