title: Checking string has balanced parentheses
body: <p>I am reading the <em>Algorithm Design Manual Second Edition</em> and this is from an exercise question. Quoting the question</p>
  
  <blockquote>
    <p>A common problem for compilers and
    text editors is determining whether
    the parentheses in a string are
    balanced and properly nested. For
    example, the string ((())())()
    contains properly nested pairs of
    parentheses, which the strings )()(
    and ()) do not. Give an algorithm that
    returns true if a string contains
    properly nested and balanced
    parentheses, and false if otherwise.
    For full credit, identify the position
    of the first offending parenthesis if
    the string is not properly nested and
    balanced.</p>
  </blockquote>
  
  <p>Question is under stacks,queues and lists category. Here is what I wrote in C#.</p>
  
  <pre><code>const char LeftParenthesis = '(';
  const char RightParenthesis = ')';
  bool AreParenthesesBalanced(string str, out int errorAt)
  {
      var items = new Stack&lt;int&gt;(str.Length);
      errorAt = -1;
      for (int i = 0; i &lt; str.Length; i++)
      {
          char c = str[i];
          if (c == LeftParenthesis)
              items.Push(i);
          else if (c == RightParenthesis)
          {
              if (items.Count == 0)
              {
                  errorAt = i + 1;
                  return false;
              }
              items.Pop();
          }
      }
      if (items.Count &gt; 0)
      {
          errorAt = items.Peek() + 1;
          return false;
      }
      return true;
  }
  </code></pre>
  
  <p>This works well. But I am not sure that this is the right method to approach this problem. Any better ideas are welcome.</p>