2023-04-10 Daily Challenge
Today I have done leetcode's April LeetCoding Challenge with cpp
.
April LeetCoding Challenge 10
Description
Valid Parentheses
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
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
Solution
class Solution {
public:
bool isValid(string s) {
vector<char> st;
for(auto c : s) {
switch(c) {
case '(':
case '[':
case '{':
st.push_back(c);
break;
case ')':
if(st.empty() || st.back() != '(') {
return false;
}
st.pop_back();
break;
case ']':
if(st.empty() || st.back() != '[') {
return false;
}
st.pop_back();
break;
case '}':
if(st.empty() || st.back() != '{') {
return false;
}
st.pop_back();
break;
default:
return false;
}
}
return st.empty();
}
};
// Accepted
// 93/93 cases passed (2 ms)
// Your runtime beats 46.33 % of cpp submissions
// Your memory usage beats 56.25 % of cpp submissions (6.4 MB)