Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Added balanced parenthesis expression validation algorithm #3563

Merged
merged 1 commit into from
Oct 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions strings/C++/Valid_parenthesis_expression.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <iostream>
#include <string>
#include <stack>
using namespace std;

class Solution {
public:
bool checkValidString(string s) {
int n = s.length();
stack<int> open, star;
for (int i = 0; i < n; i++) {
if (s[i] == '(') open.push(i); // keeping track of where open brackets are.
else if (s[i] == '*') star.push(i); // and stars
else { // s[i]==')'
if (!open.empty()) open.pop(); // if open exists
else if (!star.empty()) star.pop(); // if star exists
else return false; // if none then invalid
}
}
// stack not empty meaning open parenthesis not closed
while (!open.empty()) {
if (star.empty()) return false; // no way to validate
else {
if (open.top() > star.top()) return false; // if star happened before open bracket
else {
// star can be used as close
star.pop();
open.pop();
}
}
}
return true;
}
};

int main() {
Solution solution;
string input = "(*))";
bool isValid = solution.checkValidString(input);
if (isValid) {
cout << "The string is valid." << endl;
} else {
cout << "The string is not valid." << endl;
}
return 0;
}