Skip to content

Instantly share code, notes, and snippets.

@SH4DY
Created March 22, 2015 11:13
Show Gist options
  • Save SH4DY/bbce2ecf43c9955f720e to your computer and use it in GitHub Desktop.
Save SH4DY/bbce2ecf43c9955f720e to your computer and use it in GitHub Desktop.
. A common problem for compilers and text editors is determining whether the parentheses in a string are balanced and properly nested. For example, the string ((())())() contains properly nested pairs of parentheses, which the strings )()( and ()) do not. Give an algorithm that returns true if a string contains properly nested and balanced paren…
//return -1: correct parentheses
//return n: Position of first offending bracket
public static int parantheses(char[] chrs){
Stack s = new Stack();
int i = 0;
for(;i<chrs.length;i++){ //Checks for erroneous chars omitted
char c = chrs[i];
if(c == '('){
s.push(c);
}else{ //closing bracket
if(s.empty() || !s.peek().equals('(')){
return i; //Return pos of offending parantheses
}else{
s.pop();
}
}
}
if(!s.empty()){
return chrs.length;
}
return -1; //Everything good
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment