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的最大连续有效括号串的长度,为了方便处理第一个“(”,我先在栈里压了个'*' 号。
代码:
括号的问题都可以往栈上想。
把括号字符串顺次压栈,当 "(" 碰到 ")"时,就像2048游戏里的方块一样抵消,然后“(”前面字符的累加长度+2。
每个栈元素存的是一个char和一个int,int代表包含这个char的最大连续有效括号串的长度,为了方便处理第一个“(”,我先在栈里压了个'*' 号。
代码:
- struct item{
- char a;
- int b;
- item(char _a, int _b){
- a=_a;
- b=_b;
- }
- };
- int longestValidParentheses(string s) {
- int number=0;
- int maxnum=0;
- stack<item> st;
- st.push(item('*',0));
- for ( string::iterator it=s.begin(); it!=s.end(); ++it){
- if(st.top().a=='(' && *it==')'){
- number=st.top().b;
- st.pop();
- number+=2;
- st.top().b+=number;
- maxnum=max(maxnum,st.top().b);
- }
- else{
- st.push(item(*it,0));
- }
- }
- return maxnum;
- }
相关热门文章
给主人留下些什么吧!~~
评论热议