Sort by

recency

|

641 Discussions

|

  • + 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 == ']')
            ;  
        }
    }
    
  • + 0 comments

    Simple switch case within a for loop

    import java.util.*;
    class Solution{
    	
    	public static void main(String []argh)
    	{
    		Scanner sc = new Scanner(System.in);
    		
    		while (sc.hasNext()) {
    			String input=sc.next();
                //Complete the code
                System.out.println(isBalanced(input));
    		}
    		
    	}
        
        private static boolean isBalanced(String input) {
            if(input.length() == 0) {
                return true;
            }
            Stack<Character> stack = new Stack<>();
            for(Character c: input.toCharArray()) {
                switch(c) {
                    case '(' :
                    case '{' :
                    case '[' :
                        stack.add(c);
                        break;
                    case ')' :
                        if (stack.isEmpty() || !stack.pop().equals('('))
                            return false;
                        break;
                    case '}' :
                        if (stack.isEmpty() || !stack.pop().equals('{'))
                            return false;
                        break;
                    case ']' :
                        if (stack.isEmpty() || !stack.pop().equals('['))
                            return false;
                        break;
                    default:
                        return false;
                }
            }
            
            return stack.isEmpty();
        }
    }
    
  • + 0 comments

    Using Deque and Map (Java 15):

    import java.util.Deque;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Scanner;
    
    class Solution {
    
        private static final Map<Character, Character> brackets = Map.of(
            ')', '(',
            '}', '{',
            ']', '['
        );
        
        private static boolean check(String input) {
            Deque<Character> stack = new LinkedList<>();
    
            for (char c : input.toCharArray()) {
                if (brackets.containsKey(c)) {
                    if (stack.isEmpty()) return false;
    
                    if (brackets.get(c) != stack.removeLast()) return false;
    
                    continue;
                }
    
                stack.add(c);
            }
    
            return stack.isEmpty();
        }
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            while (sc.hasNext()) {
                boolean isBalanced = check(sc.next());
    
                System.out.println(isBalanced ? "true" : "false");
            }
    
            sc.close();
        }
    }
    
  • + 1 comment

    import java.util.*; class Solution{

    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
    
        while (sc.hasNext()) {
            String input=sc.next();
            //Complete the code
    
            Stack <Character> s = new Stack<>();
            for(int i = 0 ; i<input.length(); i++)
            {
                char  c = input.charAt(i);
    
                if(c=='{' || c=='(' ||  c=='[')
                {
                    s.push(c);
                }
               else if(s.size()!=0 && ((c=='}' && s.peek()=='{') || (c==')' && s.peek()=='(') || (c==']' && s.peek()=='[')))
               {
                s.pop();
               }
               else{
                s.push(c);
               }
    
            }
            if(s.size()==0) System.out.println("true");
            else System.out.println("false");
        }
    
    }
    

    }

  • + 0 comments

    public static void main(String []argh) { Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            String input=sc.next();
            String[] values = input.split("");
            Stack<String> stack = new Stack<>();
            Map<String, String> chars = new HashMap<>();
            chars.put("(", ")");
            chars.put("{", "}");
            chars.put("[", "]");
            boolean malformed = false;
    
            for (String value: values){
                if (chars.keySet().contains(value)){
                    stack.add(value);
                } else {
                    try{
                        String openingChar = stack.pop();
                        if (!chars.get(openingChar).equals(value)){
                            malformed = true;
                        }    
                    } catch (EmptyStackException e){
                        malformed = true;
                    }
    
                }
            }
            System.out.println(stack.isEmpty() && !malformed ? "true" : "false");
    
            //Complete the code
        }
    
    }