使用BooleanSupplier
而不是Method
.
Stack<Character> s = new Stack<>();
Map<Character, BooleanSupplier> map = new HashMap<>();
map.put('(', () -> { s.push('('); return true; });
map.put(')', () -> !s.isEmpty() && s.pop() == '(');
并像这样检查。
String str = "((ab)c)";
int errorAt = -1;
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (map.containsKey(c))
if (!map.get(c).getAsBoolean()) {
errorAt = i;
break;
}
}
if (errorAt == -1 && s.isEmpty())
System.out.println("OK!");
else if (errorAt == -1)
System.out.println("error at " + str.length()); // too few ')'
else
System.out.println("error at " + errorAt); // too many ')'
或者您可以使用 Stream API。
int errorAt = IntStream.range(0, str.length())
.filter(i -> map.containsKey(str.charAt(i)))
.reduce(-1, (p, i) -> p >= 0 || map.get(str.charAt(i)).getAsBoolean() ? p : i);