Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []
class Solution {
public:
bool isValid(string s) {
stack<char> st; //taking stack for keep tracking the order of the brackets..
for(auto i:s) //iterate over each and every elements
{
if(i=='(' or i=='{' or i=='[') st.push(i); //if current element of the string will be opening bracket then we will just simply push it into the stack
else //if control comes to else part, it means that current element is a closing bracket, so check two conditions current element matches with top of the stack and the stack must not be empty...
{
if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}') or (st.top()=='[' and i!=']')) return false;
st.pop(); //if control reaches to that line, it means we have got the right pair of brackets, so just pop it.
}
}
return st.empty(); //at last, it may possible that we left something into the stack unpair so return checking stack is empty or not..
}
};
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;
};
In our experience, we suggest you solve this Valid Parentheses LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Valid Parentheses LeetCode Solution
I hope this Valid Parentheses LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>