Compare commits

..

1 Commits

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

Loading…
Cancel
Save