day 21: 20-valid-parentheses

started neetcode roadmap, finishing easy problems first
This commit is contained in:
Kaushik Narayan R 2023-10-20 20:10:29 -07:00
parent 9ed9a1ada6
commit 42c44952c5
3 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,9 @@
#include "soln.hpp"
int main() {
string s = "({[[[]]]})";
bool answer = true;
Solution soln;
cout << "Checked parentheses correctly? " << soln.test(s, answer) << endl;
return 0;
}

View File

@ -0,0 +1,42 @@
#include "soln.hpp"
bool Solution::isValid(string s)
{
if (s.length() == 1)
return false;
vector<char> bstack;
for (char c : s)
{
switch (c)
{
case '(':
case '[':
case '{':
bstack.push_back(c);
break;
case ')':
if (bstack.size() < 1 || bstack.back() != '(')
return false;
else
bstack.pop_back();
break;
case ']':
if (bstack.size() < 1 || bstack.back() != '[')
return false;
else
bstack.pop_back();
break;
case '}':
if (bstack.size() < 1 || bstack.back() != '{')
return false;
else
bstack.pop_back();
break;
}
}
return bstack.size() == 0;
}
bool Solution::test(string s, bool answer) {
return isValid(s) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isValid(string s);
bool test(string s, bool answer);
};