Monday, November 30, 2015
Check if Parentheses are Balanced
import java.util.Stack;
class Parenthesis {
public boolean isParenthesisCorrect(String s) {
char[] c = s.toCharArray();
int size=c.length;
Stack S = new Stack<Character>();
boolean flag = true;
for(int i=0; i<size; i++) {
if(c[i]=='(')
S.push(c[i]);
else if(c[i]==')') {
if(!((Character)S.pop()=='(')) {
flag=false;
break;
}
}
}
if(!S.isEmpty())
flag=false;
return flag;
}
}
public class Main {
public static void main(String[] args) {
Parenthesis P = new Parenthesis();
String s = "((a+b)*(a-b))/c";
System.out.println(P.isParenthesisCorrect(s));
}
}
Labels:
Algorithm,
Data Structures,
Jeevan,
Jeevan Rex,
Jeevanus,
Stack
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment