码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Valid Parentheses

时间:2015-01-11 12:14:33      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

难点1,是栈,2是流程

class Solution {
public:
    int longestValidParentheses(string s) {
         stack<int> mstack;
		 char cbefore;
         int count = 0;
		 if(s.empty())
		  return 0;
		 
		 for(int i=0; i<s.size(); i++)
		 {
            
		     bool ret;
			
			 CountTotal(mstack,count);
			 if(mstack.empty())
			 {
			    if(count!=0)
			    {
					mstack.push(count);
					mstack.push(‘a‘);
					count =0;

				}
			    
				mstack.push(s[i]);
				
				continue;
			 }
           
             ret = CheckValidParentheses(mstack.top(),s[i]);
			 if(ret == false)
			 {  
				if(count!=0)
			    {
					mstack.push(count);
					mstack.push(‘a‘);
					count =0;

				}
                  mstack.push(s[i]);	  
			 }
			 else
			 {
			     mstack.pop();
			     count++;
				 mstack.push(count);
				 mstack.push(‘a‘);
				 count =0;
				 
			

			 }
			 
		 }
	    CountTotal(mstack,count);
	  int maxcount = count;
	  count =0;
	  while(!mstack.empty())
	  {
          if(mstack.top() != ‘a‘)
		  {
             mstack.pop();
			 if(count > maxcount)
			 	maxcount = count;
			 count =0;
			 continue;

		  };
		  
		  mstack.pop();
		  count+=mstack.top();
		  mstack.pop();
	  }
      if(count > maxcount)
		maxcount = count;
	   return maxcount*2;
		     
    }
	bool CheckValidParentheses(char a,char b)
	{
        if(a == ‘(‘ && b == ‘)‘)
		 return true;
		return false;

	}
	void CountTotal(stack<int>& mstack,int& count)
	{
	  
		while(1)
		{    
		  if(mstack.empty())
		  	return;
		  if(mstack.top() != ‘a‘)
		  	return;
		  
		  mstack.pop();
		  count+=mstack.top();
		  mstack.pop();
		}

	}
};

  

Longest Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/xgcode/p/4216287.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!