2 December 2014

Quiz 61: Find number of matching pairs of brackets


Problem: 

Given a sequence containing only '(' and ')' , find number of matching '()'. Example in ((()())), number of matching pairs are 4. In ()())))(), number of matching pairs are 3.

Input Format: 

Sequence

Output Format: 

Number of Matching pairs

Constraints: 

None

Sample Input

()(()()))))((()()

Sample Output:

6

Explanations:

Pairs marked in different colors are ()(()()))))((()()


Solution:

chomp($n=<STDIN>);
@arr=split(//,$n);
$c=0;
$ans=0;
foreach(@arr)
{
if($_ eq '(')
{
$c++;
}
if($_ eq ')' and $c>0)
{
$c--;
$ans++;
}
}
print $ans;




Tips:

First find '(' and then matching ')'

No comments:

Post a Comment