#include #include #include using namespace std; const int MAX_LENGTH = 100; const int INFINITY = 1000000; string buffer; int bestlen[MAX_LENGTH][MAX_LENGTH]; bool match (char c, char d){ return (c == '(' && d == ')') || (c == '[' && d == ']'); } int main (){ while (true){ cin >> buffer; if (buffer == "end") break; int L = buffer.length(); // clear out buffer for (int i = 0; i < MAX_LENGTH; i++) for (int j = 0; j < MAX_LENGTH; j++) bestlen[i][j] = 0; // dynamic programming for (int len = 2; len <= L; len++){ // find length of longest regular brackets subsequence // contained within s = buffer[i]...buffer[j] for (int i = 0; i + len - 1 < L; i++){ int j = i + len - 1; // look for all possible ways of building s from // either two smaller regular brackets subsequences // or from a regular brackets subsequence + "junk" for (int k = i; k < j; k++){ if (bestlen[i][j] < bestlen[i][k] + bestlen[k+1][j]) bestlen[i][j] = bestlen[i][k] + bestlen[k+1][j]; } // consider s of the form (s') or [s'] if (match (buffer[i], buffer[j])){ if (bestlen[i][j] < bestlen[i+1][j-1]+2) bestlen[i][j] = bestlen[i+1][j-1]+2; } } } cout << bestlen[0][L-1] << endl; } return 0; }