• + 0 comments

    Use helper method to check if balanced then return boolean if the stack is empty

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            Scanner input = new Scanner(System.in); 
            while(input.hasNext()) {
                String line = input.nextLine(); 
                Stack<Character> lineStak = new Stack<>(); 
                for (char chars : line.toCharArray()) {
                    if(lineStak.empty()) {
                        lineStak.push(chars); 
                    }
                    else if (balanced(lineStak.peek(), chars)) lineStak.pop(); 
                    else lineStak.push(chars);  
                }
                System.out.println(lineStak.empty());
                
            }
        }
        
        public static boolean balanced(char c1, char c2 ) {
            
            return 
                (c1 == '{' && c2 == '}') ||
                (c1 == '(' && c2 == ')') ||
                (c1 == '[' && c2 == ']')
            ;  
        }
    }