【原创】最长有效括号的长度
from pongo,给定只包含括号字符'('和 ')''的字符串,请找出最长的有效括号内子括号的长度。这里我使用vector来解决
// test.cpp : 定义控制台应用程序的入口点。
// editor: Visual C++ 2010 express
// system: win7 x32
// create: 2013-06-24 10:40AM
// author: jiang kejun <jinhua_k9@163.com>
#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int longestValidParentheses(string s);
int _tmain(int argc, _TCHAR* argv[])
{
longestValidParentheses("( ()");
longestValidParentheses(") () () )");
longestValidParentheses("( () () )");
scanf_s("%d", 0);
return 0;
}
int longestValidParentheses(string s)
{
int len=0,i=0,j=0;
vector<int>arr;
while(i<s.length())
{
if(s.at(i) == '(')
{
//arr[j] = 1;
arr.push_back(1);
//j++;
}
else if(s.at(i) == ')')
{
if(arr.size()>0){
//cout<<i<<"\t::\t"<<arr.size()<<endl;
arr.pop_back();
len++;
}
}
i++;
}
cout<<len<<endl;
return len;
}
result: