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