You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
is-string-well-formed/src/main/java/Solution.java

36 lines
1.2 KiB
Java

import java.util.*;
import java.util.function.BiPredicate;
class Solution {
// 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 ) );
}
}