fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8.  
  9. class Stack{
  10.  
  11. int maxSize;
  12. char[] stackArray;
  13. int top;
  14.  
  15. Stack(int s){
  16. maxSize=s;
  17. stackArray=new char[maxSize];
  18. top=-1;
  19. }
  20.  
  21.  
  22. public void push(char j){
  23.  
  24. stackArray[++top]=j;
  25.  
  26. }
  27.  
  28. public char pop(){
  29.  
  30. return stackArray[top--];
  31. }
  32.  
  33. public boolean isEmpty(){
  34.  
  35. return (top ==-1)? true :false;
  36. }
  37.  
  38. public boolean isFull(){
  39.  
  40. return false;
  41. }
  42.  
  43.  
  44. }
  45.  
  46. class Ideone
  47. {
  48.  
  49. static boolean balancedParenthsis(char c1,char c2){
  50.  
  51. if(c1=='{' && c2=='}'){
  52. return true;
  53. }
  54. else if(c1 == '(' && c2 == ')' ){
  55. return true;
  56. }
  57. else if(c1=='[' && c2==']'){
  58. return true;
  59. }
  60. else{
  61. return false;
  62. }
  63. }
  64.  
  65. static boolean isParenthesisBalanced(char[] exp){
  66.  
  67. int size=exp.length;
  68. Stack stack=new Stack(size);
  69.  
  70. for(int i=0;i<size;i++){
  71.  
  72. if(exp[i]=='{'||exp[i]=='('|| exp[i]=='['){
  73. stack.push(exp[i]);
  74. }
  75.  
  76. if(exp[i]=='}'||exp[i]==')'|| exp[i]==']'){
  77.  
  78. if(stack.isEmpty()){
  79. return false;
  80. }
  81. else if(!balancedParenthsis(stack.pop(),exp[i])){
  82. return false;
  83. }
  84.  
  85. }
  86.  
  87.  
  88. }
  89.  
  90.  
  91. if(stack.isEmpty()){
  92. return true;
  93. }
  94. else{
  95. return false;
  96. }
  97.  
  98.  
  99. }
  100. public static void main (String[] args) throws java.lang.Exception
  101. {
  102. // your code goes here
  103. Scanner sc=new Scanner(System.in);
  104. String s=sc.nextLine();
  105.  
  106. //char[] ch=new char[s.length()];
  107.  
  108. char[] ch=s.toCharArray();
  109.  
  110. for(int i=0;i<s.length();i++){
  111.  
  112. //ch=s.charAt[i];
  113. System.out.print(ch[i]+" ");
  114. }
  115. if(isParenthesisBalanced(ch)){
  116. System.out.print("Balanced");
  117. }
  118. else{
  119. System.out.print("Not Balanced");
  120. }
  121. }
  122. }
Success #stdin #stdout 0.07s 4386816KB
stdin
{{()[]}}
stdout
{ { ( ) [ ] } } Balanced