fork download
  1. #!/usr/bin/env perl
  2. use 5.010;
  3. use strict;
  4. use warnings;
  5.  
  6. my @tests =
  7. ( "", "( )", "{ ( { ( ) } ( ) ) } ( )", "} {", "( { ) }", "{ } ( { } )", );
  8. my $lefts = qr< [{(] >x;
  9. my $rights = qr< [)}] >x;
  10. my %pair_for = (
  11. ')' => '(',
  12. '}' => '{',
  13. );
  14.  
  15. my ( $twin, $i, $err, $max_so_far );
  16. $twin = qr{
  17. (?> [^(){}]* )
  18. ($lefts)
  19. (?{$max_so_far = $i if $max_so_far < ++$i})
  20. (?:
  21. (?> [^(){}]+ )
  22. |
  23. (??{$twin})
  24. )*
  25. ($rights)
  26. (?{--$i})
  27. (?{ unless ($1 eq $pair_for{$2}){++$err} })
  28. }x;
  29.  
  30. for my $test (@tests) {
  31. ( $i, $err, $max_so_far ) = ( 0, 0, 0 );
  32. print q("), $test, q("), q( => );
  33. say 0 and next unless $test;
  34. ( $test =~ / $twin+ /xg and $err == 0 ) ? say "$max_so_far"
  35. : say -1
  36. ;
  37. }
Success #stdin #stdout 0s 5404KB
stdin
Standard input is empty
stdout
"" => 0
"( )" => 1
"{ ( { ( ) } ( ) ) } ( )" => 4
"} {" => -1
"( { ) }" => -1
"{ } ( { } )" => 2