Question 1342: Search for the longest legal bracket sequence II (25 points)
Time Limit: 1 second
Memory limit: 32 MB
Special question: No
Submit: 527
Solution: 216
Description:
If you are given a random sequence of parentheses consisting of '(' and ')', of course, this sequence of parentheses cannot be guaranteed to be matching between left and right brackets, therefore, the task is to remove some of the parentheses, so that the remaining parentheses can match and have the longest length, that is, the longest legal parenthesis sequence.
Input:
There are multiple test data. Each test data has only one row, that is, a random sequence of parentheses. The length of the sequence must not exceed 106.
Output:
For each test case, an integer is output, indicating the length of the last longest legal parentheses sequence.
Sample input:
(())()
() Sample output:
6
2. Algorithm Analysis
In one sentence, several pairs of parentheses can be found from left to right.
Use Lnum to indicate that several single '(',
When '(', Lnum ++;
When ')' is encountered, if Lnum> 0, it indicates that there is a single '(', current ')' in front of it and a '(') in front of it, A single '(' is missing, so Lnum minus 1. Because a new pair of '(', ')' is added, maxLen + = 2;
There is also a sequence question with the longest legal parentheses, but the algorithm is quite different. See 1337 of 9-degree notes: Searching for the longest legal sequence of parentheses
Source program
//============================================================================// Name : judo1342new.cpp// Author : wdy// Version :// Copyright : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================//similar to 1337//similar to 1260#include <iostream>using namespace std; void getMaxLen(std::string &s){ std::string::size_type len = s.size(); std::string::size_type pos = 0; int Lnum = 0; //int Rnum = 0; int maxLen = 0; for(pos = 0;pos<len;pos++){ if(s.at(pos)=='(') ++Lnum; else if(Lnum>0){ --Lnum; maxLen+=2; } }//for std::cout<<maxLen<<std::endl;} void judo(){ std::string s; while(std::cin>>s){ getMaxLen(s); }}int main() { judo(); //cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0;} /************************************************************** Problem: 1342 User: KES Language: C++ Result: Accepted Time:220 ms Memory:3052 kb****************************************************************/