Compare commits

..

1 Commits

@ -1,42 +1,35 @@
import java.util.*; import java.util.*;
import java.util.function.BiPredicate;
/**
* Template code to help you parse the standard input
* according to the problem statement.
**/
class Solution { class Solution {
public static void main( String[] args ) { // best readable version, also without dark ASCII code tricks
Scanner in = new Scanner( System.in ); private static final BiPredicate<Integer, Integer> BRACKETS_MATCH = ( c1, c2 ) -> ( c1 != null && c2 != null )
// read values with in.next...() methods && (( c1 == '(' && c2 == ')' ) || ( c1 == '[' && c2 == ']' ) || ( c1 == '{' && c2 == '}' ));
String input = in.nextLine();
// code your solution here // code your solution here
boolean output = isInputWellFormed(input); private static boolean checkNextChar( Deque<Integer> stack, Iterator<Integer> iter ) {
// Write result with System.out.println() if ( ! iter.hasNext() ) return stack.isEmpty();
System.out.println( output );
} int c = iter.next();
if ( BRACKETS_MATCH.test( stack.peek(), c )) {
private static boolean isInputWellFormed(String input) { stack.pop();
HashMap<Character, Character> validPairs = new HashMap<>(); }
validPairs.put('{', '}'); else {
validPairs.put('(', ')'); stack.push( c );
validPairs.put('[', ']'); }
Deque<Character> unmatchedChars = new ArrayDeque<>(); return checkNextChar( stack, iter );
}
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i); public static void main( String[] args ) {
// hint: read values via Scanner methods
if (validPairs.keySet().contains(currentChar)) { var inputLine = new Scanner( System.in ).nextLine();
unmatchedChars.push(currentChar); // Add only opening ({[ to the unmatchedChars.
} else if (validPairs.values().contains(currentChar)) { var stack = new ArrayDeque<Integer>( inputLine.length() );
if (!unmatchedChars.isEmpty() && validPairs.get(unmatchedChars.peekFirst()) == currentChar) { var iter = inputLine.chars().iterator();
unmatchedChars.pop(); // Match found, empty the unmatchedChars.
} else { // Write result with System.out.println()
return false; System.out.println( checkNextChar( stack, iter ) );
} }
}
}
return unmatchedChars.isEmpty();
}
} }

Loading…
Cancel
Save