1 Commits

Author SHA1 Message Date
048f165373 my solution 2020-04-30 08:10:02 +02:00

View File

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