Skip to content

Instantly share code, notes, and snippets.

@abhilash0001
Created July 19, 2017 20:27
Show Gist options
  • Save abhilash0001/e81e70927bbed89a5041202157c1ecb2 to your computer and use it in GitHub Desktop.
Save abhilash0001/e81e70927bbed89a5041202157c1ecb2 to your computer and use it in GitHub Desktop.
Parenthesis Balancing
// Stack Implementation
const char leftParenthesis = '(';
const char rightParenthesis = ')';
const string inputStr = "((())())()()";
public bool checkIfBalanced(){
var items = new Stack<int>(inputStr.Length);
for(int i = 0; i < inputStr.Length; i++){
char c = inputStr[i];
if (c == leftParenthesis){
items.Push(i);
}
else if (c == rightParenthesis){
if (items.Count == 0)
return false;
items.Pop();
}
}
if (items.Count > 0)
return false;
return true;
}
Console.WriteLine(checkIfBalanced());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment