Created
March 22, 2015 11:13
-
-
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…
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
//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