Created
December 4, 2018 14:46
-
-
Save PeteGabriel/5c98ab76e38fb01c42537882906e59ac to your computer and use it in GitHub Desktop.
Get closing parenthesis for opening position
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
public class Parenthesis | |
{ | |
public static int GetClosingParenthesis(string input, int openingPos) | |
{ | |
var counter = 0; | |
var positionFound = -1; | |
for (int i = 0; i < input.Length; i++) | |
{ | |
if (input[i] == '(' && openingPos == i) | |
{ | |
counter += 1; | |
} | |
if (input[i] == ')') | |
{ | |
//we've found a valid closing match but input is | |
//unbalanced. | |
if (counter == 0 && positionFound != -1) | |
{ | |
return -1; | |
} | |
counter -= 1; | |
if (counter == 0) | |
{ | |
positionFound = i; | |
} | |
} | |
} | |
return positionFound; | |
} | |
} | |
[Fact] | |
public void GetClosingIndexForGivenPositionWithCorrectInput() | |
{ | |
var input = "Hello miss Hanna (how are you today?)"; | |
var openingPos = 17; | |
var expectedClosingPos = 36; | |
Assert.Equal(expectedClosingPos, Parenthesis.GetClosingParenthesis(input, openingPos)); | |
} | |
[Fact] | |
public void GetClosingIndexForGivenPositionWithManyParenthesis() | |
{ | |
var input = "Hello miss Hanna (how (are) (you) today?)"; | |
var openingPos = 17; | |
var expectedClosingPos = 40; | |
Assert.Equal(expectedClosingPos, Parenthesis.GetClosingParenthesis(input, openingPos)); | |
} | |
[Fact] | |
public void GetClosingIndexForGivenPositionWithUnbalancedInput() | |
{ | |
var input = "Hello miss Hanna (how )areyou) today?)"; | |
var openingPos = 17; | |
var expectedClosingPos = -1; | |
Assert.Equal(expectedClosingPos, Parenthesis.GetClosingParenthesis(input, openingPos)); | |
} | |
[Fact] | |
public void GetClosingIndexForGivenPositionWithNoInputt() | |
{ | |
var input = "Hello miss Hanna. How are you today?"; | |
var openingPos = 17; | |
var expectedClosingPos = -1; | |
Assert.Equal(expectedClosingPos, Parenthesis.GetClosingParenthesis(input, openingPos)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment