您的位置:首页 > 其它

LeetCode 32. Longest Valid Parentheses

2016-05-06 07:34 369 查看
#include <string>
#include <vector>
#include <iostream>
using namespace std;

/*
Given a string containing just the character '(' and ')', find the length of the longest
valid parentheses substring.
for "(()", the longest valid parentheses substring is  "()" which has length 2.
Another example ")()())", where the longest valid parentheses substring is "()()", which
has length 4.
*/

// Use one pointer always points to the end index of vector.

int longestValidParentheses(string s) {
if(s.size() <= 1) return 0;
vector<int> index;
int maxSize = 0;
for(int i = 0; i < s.size(); ++i) {
if(s[i] == '(') {
index.push_back(i);   // push the index number.
} else {
if(!index.empty() && s[index.back()] == '(') {
index.pop_back();
int lastPos = -1;
if(!index.empty()) {
lastPos = index.back();
}
maxSize = max(maxSize, i - lastPos);
} else {
index.push_back(i);
}
}
}
return maxSize;
}

int main(void) {
cout << longestValidParentheses("())()") << endl;
}
~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: