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 pairsConstraints:
NoneSample Input
()(()()))))((()()
Sample Output:
6Explanations:
Pairs marked in different colors are ()(()()))))((()()
Solution:
@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