Monday, October 21, 2013

Solution to LeetCode Problems: Valid Parentheses

Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Thoughts:
A stack should do the job. 

Solution:
  1. class Solution {  
  2. public:  
  3.     char counterPart(const char ch)  
  4.     {  
  5.         switch(ch)  
  6.         {  
  7.             case '{':  
  8.                 return '}';  
  9.             case '[':  
  10.                 return ']';  
  11.             case '(':  
  12.                 return ')';  
  13.             default:  
  14.                 return 0;  
  15.         }  
  16.     }  
  17.   
  18.     bool isValid(string s) {  
  19.         stack<char> parenthesis;  
  20.           
  21.         for(auto ch: s)  
  22.             if (ch == '(' || ch == '[' || ch == '{')  
  23.                 parenthesis.push(ch);  
  24.             else  
  25.                 if (!parenthesis.empty() && ch == counterPart(parenthesis.top()))  
  26.                     parenthesis.pop();  
  27.                 else  
  28.                     return false;  
  29.           
  30.         return parenthesis.empty();  
  31.     }  
  32. };  

No comments:

Post a Comment