commit cf1189cc092fdcbcac692029e234be4ff060bcb2 parent 26ff224f42305cd88b999873c5759d0e9b396ac8 Author: AndrewLockVI <andrewlaack1@gmail.com> Date: Sun, 9 Apr 2023 18:06:10 -0500 Completed valid parenthesis using list as stack Diffstat:
| A | valid-parenthesis/valid-parenthesis.cpp | | | 63 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 63 insertions(+), 0 deletions(-)
diff --git a/valid-parenthesis/valid-parenthesis.cpp b/valid-parenthesis/valid-parenthesis.cpp @@ -0,0 +1,63 @@ +#include <iostream> +#include <list> + + +//Leet Ratings +// Speed Memory +//Total 0ms 6.4MB +//Beats 100% 12.9% + + +using namespace std; + + +//Get matching parentheses for right side. +char get_match(char input){ + if(input == ')'){ + return '('; + } + if(input == '}'){ + return '{'; + } + if(input == ']'){ + return '['; + } + return 'e'; +} + +//Check if parentheses are valid using a stack then checking at the end the the stack is empty. +bool isValid(string s) { + list<char> stack; + for(int i = 0 ; i < s.size() ; ++i){ + if(get_match(s[i]) == 'e'){ + stack.push_front(s[i]); + } + else{ + if(stack.front() == get_match(s[i]) ){ + stack.pop_front(); + } + else{ + return false; + } + } + } + if(stack.empty()){ + return true; + } + else{ + return false; + } +} + + + + +int main(){ + cout << "Input parenthesis set to check: "; + string s; + cin >> s; + cout << boolalpha; + cout << isValid(s) << endl; + + +}