Chinaunix首页 | 论坛 | 博客
  • 博客访问: 117332
  • 博文数量: 53
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-24 16:22
文章存档

2014年(53)

我的朋友

分类: C/C++

2014-10-07 14:55:35

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.


Have you been asked this question in an interview?

括号的问题都可以往栈上想。

把括号字符串顺次压栈,当 "(" 碰到 ")"时,就像2048游戏里的方块一样抵消,然后“(”前面字符的累加长度+2。

每个栈元素存的是一个char和一个int,int代表包含这个char的最大连续有效括号串的长度,为了方便处理第一个“(”,我先在栈里压了个'*' 号。

代码:

  1. struct item{
  2.     char a;
  3.     int b;
  4.     item(char _a, int _b){
  5.         a=_a;
  6.         b=_b;
  7.     }
  8. };
  9. int longestValidParentheses(string s) {
  10.     int number=0;
  11.     int maxnum=0;
  12.     stack<item> st;
  13.     st.push(item('*',0));
  14.     for ( string::iterator it=s.begin(); it!=s.end(); ++it){
  15.         if(st.top().a=='(' && *it==')'){
  16.            number=st.top().b;
  17.             st.pop();
  18.             number+=2;
  19.             st.top().b+=number;
  20.             maxnum=max(maxnum,st.top().b);
  21.         }
  22.         else{
  23.             st.push(item(*it,0));
  24.         }
  25.     }
  26.     return maxnum;
  27. }



阅读(1001) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~