#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
my @tests =
( "", "( )", "{ ( { ( ) } ( ) ) } ( )", "} {", "( { ) }", "{ } ( { } )", );
my $lefts = qr< [{(] >x;
my $rights = qr< [)}] >x;
my %pair_for = (
')' => '(',
'}' => '{',
);
my ( $twin, $i, $err, $max_so_far );
(?> [^(){}]* )
($lefts)
(?{$max_so_far = $i if $max_so_far < ++$i})
(?:
(?> [^(){}]+ )
|
(??{$twin})
)*
($rights)
(?{--$i})
(?{ unless ($1 eq $pair_for{$2}){++$err} })
}x;
for my $test (@tests) {
( $i, $err, $max_so_far ) = ( 0, 0, 0 );
say 0 and next unless $test;
( $test =~ / $twin+ /xg and $err == 0 ) ? say "$max_so_far"
: say -1
;
}
IyEvdXNyL2Jpbi9lbnYgcGVybAp1c2UgNS4wMTA7CnVzZSBzdHJpY3Q7CnVzZSB3YXJuaW5nczsKCm15IEB0ZXN0cyA9CiAgKCAiIiwgIiggKSIsICJ7ICggeyAoICkgfSAoICkgKSB9ICggKSIsICJ9IHsiLCAiKCB7ICkgfSIsICJ7IH0gKCB7IH0gKSIsICk7Cm15ICRsZWZ0cyAgICAgID0gcXI8IFt7KF0gPng7Cm15ICRyaWdodHMgICAgID0gcXI8IFspfV0gPng7Cm15ICVwYWlyX2ZvciA9ICgKICAgICcpJyA9PiAnKCcsCiAgICAnfScgPT4gJ3snLAopOwoKbXkgKCAkdHdpbiwgJGksICRlcnIsICRtYXhfc29fZmFyICk7CiR0d2luID0gcXJ7CiAgICAgICAgICAgICg/PiBbXigpe31dKiApCiAgICAgICAgICAgICgkbGVmdHMpCiAgICAgICAgICAgICg/eyRtYXhfc29fZmFyID0gJGkgaWYgJG1heF9zb19mYXIgPCArKyRpfSkKICAgICAgICAgICAgKD86CiAgICAgICAgICAgICAgICAoPz4gW14oKXt9XSsgKQogICAgICAgICAgICB8CiAgICAgICAgICAgICAgICAoPz97JHR3aW59KQogICAgICAgICAgICApKgogICAgICAgICAgICAoJHJpZ2h0cykKICAgICAgICAgICAgKD97LS0kaX0pCiAgICAgICAgICAgICg/eyB1bmxlc3MgKCQxIGVxICRwYWlyX2ZvcnskMn0peysrJGVycn0gfSkKfXg7Cgpmb3IgbXkgJHRlc3QgKEB0ZXN0cykgewogICAgKCAkaSwgJGVyciwgJG1heF9zb19mYXIgKSA9ICggMCwgMCwgMCApOwogICAgcHJpbnQgcSgiKSwgJHRlc3QsIHEoIiksIHEoID0+ICk7CiAgICBzYXkgMCBhbmQgbmV4dCB1bmxlc3MgJHRlc3Q7CiAgICAoICR0ZXN0ID1+IC8gJHR3aW4rIC94ZyBhbmQgJGVyciA9PSAwICkgPyBzYXkgIiRtYXhfc29fZmFyIgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDogc2F5IC0xCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgOwp9