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

Loading…
Cancel
Save