leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

valid-parenthesis.cpp (1086B)


      1 #include <iostream>
      2 #include <list>
      3 
      4 
      5 //Leet Ratings
      6 //       Speed  Memory
      7 //Total  0ms    6.4MB    
      8 //Beats  100%   12.9%
      9 
     10 
     11 using namespace std;
     12 
     13 
     14 //Get matching parentheses for right side.
     15 char get_match(char input){
     16     if(input == ')'){
     17         return '(';
     18     }
     19     if(input == '}'){
     20         return '{';
     21     }
     22     if(input == ']'){
     23         return '[';
     24     }
     25     return 'e';
     26 }
     27 
     28 //Check if parentheses are valid using a stack then checking at the end the the stack is empty.
     29 bool isValid(string s) {
     30     list<char> stack;
     31     for(int i = 0 ; i < s.size() ; ++i){
     32         if(get_match(s[i]) == 'e'){
     33             stack.push_front(s[i]);
     34         }
     35         else{
     36             if(stack.front() == get_match(s[i]) ){
     37                 stack.pop_front();
     38             }
     39             else{
     40                 return false;
     41             }
     42         }
     43     }
     44     if(stack.empty()){
     45         return true;    
     46     }
     47     else{
     48         return false;
     49     }
     50 }
     51 
     52 
     53 
     54 
     55 int main(){
     56     cout << "Input parenthesis set to check: ";
     57     string s;
     58     cin >> s;
     59     cout << boolalpha;
     60     cout << isValid(s) << endl;
     61 
     62 
     63 }