• + 4 comments

    My Java Solution

    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class Solution {
    
    public static boolean isBalanced(String s) {
       int len=s.length();
        if(len==0 || s==null) return true;
          Stack<Character> stack = new Stack<Character>();
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{')  stack.push(s.charAt(i));
            else if(s.charAt(i)==')' && !stack.empty() && stack.peek()=='(') stack.pop();
            else if(s.charAt(i)==']' && !stack.empty() && stack.peek()=='[') stack.pop();
    
            else if(s.charAt(i)=='}' && !stack.empty() && stack.peek()=='{') stack.pop();
            else return false;
    
    
        }
        return stack.empty();
        }
    
        public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int a0 = 0; a0 < t; a0++) {
            String expression = in.next();
            System.out.println( (isBalanced(expression)) ? "YES" : "NO" );
        }
    }
    }
    
    • + 1 comment
      else if(str.charAt(i)==']' && s.peek()=='[' && !s.empty())
      

      Please reply .. If we write the statement on either side of && as the order shown above ( peek before and empty after) , it is showing runtime error . Is the order of statement also important in writing these expressions ?

      • + 0 comments

        Yes it is. If !s.empty() is placed first and the stack is empty, s.peek()=='[' will not be executed, hence no runtime error.This is due to the short circuit evaluation nature of if statements. However the order you gave above gives runtime error because s.peek()=='[' is executed first and this may cause errors if the stack is empty.

    • + 2 comments

      Another questionisthat why !s.empty() is even required in the ?

      • + 0 comments

        I think You can't pop is stack is empty

      • + 0 comments

        If stack is not empty... then there is an extra unbalanced parenthesis on the stack...

    • + 1 comment

      My code looks exactly like your code but still I'm not able to pass 3 test cases...

      import java.util.Scanner;
      import java.util.Stack;
      
      /**
       * Created by BK on 06-08-2017.
       */
      
      public class BalancedParanthesis {
          public static void main(String... strings) {
              Scanner sc = new Scanner(System.in);
              int tc = sc.nextInt();
              for (int i = 0; i < tc; i++) {
                  printAnswer(sc.next());
              }
          }
      
          private static void printAnswer(String input) {
              Stack<Character> stack = new Stack<>();
              boolean isValid=true;
              for (int i = 0; i < input.length(); i++) {
                  char currentChar = input.charAt(i);
                  if (currentChar == '{' || currentChar == '(' || currentChar == '[') stack.push(currentChar);
                  else if (currentChar == '}') {
                      if (stack.isEmpty())isValid=false;
                      else {
                          if (stack.pop() != '{') {
                              isValid=false;
                          }
                      }
                  } else if (currentChar == ')') {
                      if (stack.isEmpty())isValid=false;
                      else {
                          if (stack.pop() != '(') {
                              isValid=false;
                          }
                      }
                  } else if (currentChar == ']') {
                      if (stack.isEmpty())isValid=false;
                      else {
                          if (stack.pop() != '[') {
                              isValid=false;
                          }
                      }
                  }
              }
              System.out.println(isValid?"YES":"NO");
          }
      }
      
      • + 1 comment

        import java.util.Scanner; import java.util.Stack;

        public class Solution {

        static String isBalanced(String s) {
            Stack stack = new Stack();
            stack.push(s.charAt(0));
            char peek;
            char charAt;
        
            for (int i = 1; i < s.length(); i++) {
                try {
                    peek = (char) stack.peek();
                    charAt = s.charAt(i);
                    if(!stack.empty()) {
                    if ((charAt == '}' && peek == '{') || (charAt == ')' && peek == '(')
                            || (charAt == ']' && peek == '[')) {
                        stack.pop();
                    } else
                        stack.push(charAt);
                    }
                    else
                        stack.push(i);
                } catch (Exception e) {
                    //i++;
                    charAt = s.charAt(i);
                    stack.push(charAt);
                }
            }
            if (stack.empty())
                return "YES";
            else
                return "NO";
        
        }
        
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int t = in.nextInt();
            in.nextLine();
            String result[] = new String[t];
            for (int a0 = 0; a0 < t; a0++) {
                String s = in.next();
                result[a0] = isBalanced(s);
            }
            in.close();
            for (int i = 0; i < t; i++)
                System.out.println(result[i]);
        }
        

        }

        • + 0 comments

          one query: If stack is empty then peek should return null. Is there any need for this check "!stack.empty() "

    • + 0 comments

      if you put one more check i.e, **if (!(s.length()%2 ==0) ) ** before for loop it will improve it's performance and many cases straight forward it will be passed