1 / 4
Jul 2020

All test cases produce correct outputs. I read the comments about output formatting and tried using System.out.print(…+ “\r”) instead of println to no avail. Should I be using a different type of input/output eg BufferedReader or PrintStream? Would appreciate any tips.

> Blockquote
    public class Main {
    	public static void main(String[] args) {
    		LinkedList<String> out = new LinkedList<String>();
    		Scanner sc = new Scanner(System.in);
    		int lncount = 1;
    		while(sc.hasNextLine()) {
    			char[] in = sc.nextLine().toCharArray();
    			if(in[0]=='-') break;
    			LinkedList<Character> process = new LinkedList<Character>();
    			int operations = 0;
    			int openstacked = 0;
    			for(int i=0; i<in.length; i++) {
    				char c = in[i];
    				if(c=='{') openstacked++;
    				else if(c=='}') {
    					if(openstacked==0) process.add(c);
    					else openstacked--;
    				}
    			}
    			if(openstacked>0) for(int i=0; i<openstacked; i++) process.add('{');
    			while(process.size()>0) {
    				if(process.get(0)!='{') operations++;
    				if(process.get(process.size()-1)!='}') operations++;
    				process.remove(0);
    				process.remove(process.size()-1);
    			}
    			out.add(lncount+". "+operations+"\r");
    			lncount ++;
    		}
    		sc.close();
    		for(int i=0; i<out.size(); i++)
    			System.out.print(out.get(i));
    	}
    }
  • created

    Jul '20
  • last reply

    Jul '20
  • 3

    replies

  • 528

    views

  • 2

    users

  • 1

    like

  • 1

    link

No they don’t, try these two:

{}}}{{
{{}}{{}{}}{}}{{}{{{}}}}}}}}{{{

Expected answers are 2 and 5.

ANARC09A

Thanks a lot for the new test cases. Was able to get AC with some adjustments to my logic, namely having the algo adjust the first and last instead of removing them, and reevaluating each time. There’s probably a better way to do this, with smaller complexity, but it feels good to know I’ve at least fixed the issue. Curious as to how you came up with these cases? I was trying to come up with my own but couldn’t stump my original code.

I created some proper bracket sequences, turned a few around, ran it through my solution, and compared the results to yours.