Skip to content

Instantly share code, notes, and snippets.

@PeteGabriel
Created December 4, 2018 14:46
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 PeteGabriel/5c98ab76e38fb01c42537882906e59ac to your computer and use it in GitHub Desktop.
Save PeteGabriel/5c98ab76e38fb01c42537882906e59ac to your computer and use it in GitHub Desktop.
Get closing parenthesis for opening position
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