Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 29, 2018 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/43a67afaac33dbe4ec87b89f7ca2c081 to your computer and use it in GitHub Desktop.
Save jianminchen/43a67afaac33dbe4ec87b89f7ca2c081 to your computer and use it in GitHub Desktop.
Open bracket - write the algorithm on April 28, 2018 - 8:00 PM mock interview
using System;
class Solution
{
public static int BracketMatch(string text)
{
if(text == null)
return 0;
var length = text.Length;
var openBracket = 0;
var unmatchedCloseBracket = 0;
for(int index = 0; index < length; index++)
{
if(text[index] == '(')
{
openBracket++;
}
else
{
if(openBracket > 0)
openBracket--;
else
unmatchedCloseBracket++;
}
}
return openBracket + unmatchedCloseBracket;
}
static void Main(string[] args)
{
}
}
/*
keywords:
open bracker/ closing bracket
(() - 1 unmatched open bracket, it may be first or second one
(()) - 0 matched
())( - (), )( - 2 unmatched
Idea: openBracket
unmatchedCloseBracket
find a (, increment variable openBracket;
find a ), to see if there is an open bracket, then openBracket--;
otherwise unmatchedCloseBracket++
return openBracket + unmatchedCloseBracket
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment