Sunday, January 22, 2012

Nested Parentheses

Problem: Write a program to determine if a string consists of properly nested parentheses

Input:
()()
(()())
(()
())(
((()))

Output:
YES
YES
NO
NO
YES

Solution 1 (using stack):
<?php
  $input = "(()())";
  $stack = array();
  $check = true;

  echo $input;
  echo "<br>";

  if(substr($input, 0, 1) == '(')
  {
    for($i=0, $n=strlen($input); $i<$n; $i++)
    {
      if(substr($input, $i, 1) == '(')
      {
        array_push($stack, substr($input, $i, 1));
      }
      elseif(substr($input, $i, 1) == ')')
      {
        if(count($stack) != 0)
        {
          array_pop($stack);
        }
        else
        {
          $check = false;
        }
      }
    }
  }
  else
  {
    $check = false;
  }

  if(count($stack) == 0)
  {
    echo $check ? "YES" : "NO";
  }
  else
  {
    echo "NO";
  }
?>

Solution 2 (using a counter):
<?php
  $input = "(()())";
  $open = 0;
  $check = true;

  echo $input;
  echo "<br>";

  if(substr($input, 0, 1) == '(')
  {
    for($i=0, $n=strlen($input); $i<$n; $i++)
    {
      if(substr($input, $i, 1) == '(')
      {
        $open++;
      }
      elseif(substr($input, $i, 1) == ')')
      {
        if($open != 0)
        {
          $open--;
        }
        else
        {
          $check = false;
        }
      }
    }
  }
  else
  {
    $check = false;
  }

  if($open == 0)
  {
    echo $check ? "YES" : "NO";
  }
  else
  {
    echo "NO";
  }
?>

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...