Created
April 29, 2018 04:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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