- 很久没写博客了,针对之前笔试做的题目,分享一个我的思路,可能在算法空间上不是最佳,希望多家多多指点;
- 这里考虑使用vector来实现匹配括号统计,并将成对括号存到vector中,使用栈可以实现同样的效果,这里使用vector在扩容上有一定性能损失;
- 该算法中将第一个括号字符均存入,在最后统计的时候根据最后一个字符来判断,判决最大括号数目是max还是max-1;
- 题目主要要求为:
-
给定一个只包含
'('
和')'
的字符串,找出最长的包含有效括号的子串的长度。示例 1:输入: "(()" 输出: 2 解释: 最长有效括号子串为
"()"
-
示例 2:输入: "
)()())
" 输出: 4 解释: 最长有效括号子串为"()()"
-
算法实现如下:
#include<iostream>
#include<vector>
using namespace std;
int main(){
int max = 0;
string str;
std::getline(std::cin, str);
const char*pchar = str.c_str();
vector<char> brc;
while (*pchar != '\0')
{
if (*pchar == '(' || *pchar == ')')
brc.push_back(*pchar);
pchar++;
}
vector<vector<char>> last;
vector<char>midch;
for (auto iter = brc.begin(); iter != brc.end(); iter++)
{
if (midch.size() > 0) {
const auto itx = midch.end() - 1;
if ((*iter == '('&&*itx == ')') || (*iter == ')'&&*itx == '('))
{
midch.push_back(*iter);
if (iter == brc.end() - 1)
last.push_back(midch);
}
else
{
last.push_back(midch);
midch.clear();
if (*iter == '(')
midch.push_back(*iter);
}
}
else
{
if (*iter == '(')
midch.push_back(*iter);
}
}
for (auto it = last.begin(); it != last.end(); ++it)
{
if ((*it).size() > max && (*((*it).end() - 1) == ')'))
max = (*it).size();
if ((*it).size() > max && (*((*it).end() - 1) == '('))
{
max = (*it).size() - 1;
}
}
std::cout << max << endl;
return 0;
}