Compare commits

..

1 Commits

View File

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