Monday, December 30, 2013

[LeetCode] Valid Parentheses


Link : Valid Parentheses

Analysis:
At first, I try to count number of each kind of parentheses in a variable, when meeting left part, increase by 1, and when meeting paired right part, decrease by 1.  If any variable below 0, return false. And if any count is not equal to 0, it is not a valid-parentheses string.

But the problem is the order of occurrence of different kind of parentheses. Counting only makes sure right part doesn't appear before left part, but cannot guarantee ([)] will return false.

I refer to http://blog.unieagle.net/2012/11/06/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Avalid-parentheses/.



Code is as below.

 class Solution {  
 public:  
   bool isValid(string s) {  
     if(s.size()==0)  
       return true;  
     stack<char> left;  
     for(int i=0; i<s.size(); i++)  
     {  
       char c = s[i];  
       if(c=='('||c=='['||c=='{')  
         left.push(c);  
       else  
       {  
         if(left.size()==0)  
           return false;  
         char pre = left.top();  
         if((pre=='(' && c==')') || (pre=='[' && c==']') || (pre=='{' && c=='}'))  
         {  
           left.pop();  
           continue;  
         }  
         return false;  
       }  
     }  
     if(left.size()==0)  
       return true;  
     else  
       return false;  
   }  
 };  

No comments:

Post a Comment