プログラマメモ2 - programmer no memo2

1145 - ツリー合算? 2011/09/19

1145 -- Tree Summing
Javaです。
自前で、パースしていてマイナスを考慮せずWA。もうわからなかったので、 discussみて、下記のinputが下記のoutputになれば通りました。
Detail of message

input:
22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3 
     (2 (4 () () )
        (8 () () ) )
     (1 (6 () () )
        (4 () () ) ) )
0 ()
-6 (3(-9()())())
9 (5(4(3(2()())())())())
output:
yes
no
yes
no
yes
no

scannerとPushbackReaderをあわせてつかってよくわからないコードに.... スタックつかってます。
package p1145_treesumming; import java.io.IOException; import java.io.PushbackReader; import java.io.StringReader; import java.util.Scanner; import java.util.Stack; public class Main { static class Val { Integer i; boolean notEnd = false; boolean noNum = false; public Val(int i) { this.i = i; } } static void find(StringBuilder builder, PushbackReader reader, Stack<Val> stack) throws IOException { int c = reader.read(); if (!((char) c == '-' || ('0' <= (char) c && (char) c <= '9'))) { int i = Integer.parseInt(builder.toString()); if (!stack.isEmpty()) { stack.lastElement().notEnd = true; } stack.add(new Val(i)); reader.unread(c); return; } builder.append((char) c); find(builder, reader, stack); } static boolean f(PushbackReader reader) throws IOException { int c = reader.read(); boolean b = false; if (')' == (char) c) { b = true; } reader.unread(c); return b; } static int n(PushbackReader reader) throws IOException { int c = reader.read(); if (c == -1) return -1; StringBuilder builder = new StringBuilder(); while ((char) c == '-' || ('0' <= (char) c && (char) c <= '9')) { builder.append((char) c); c = reader.read(); } reader.unread(c); if (builder.length() == 0) return -1; int i = Integer.parseInt(builder.toString()); return i; } public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); // PushbackReader reader = new PushbackReader(new InputStreamReader( // System.in)); do { int n = scanner.nextInt(); // int n = n(reader); Stack<Val> stack = new Stack<Val>(); boolean b = false; // if(n == -1) break; A: while (true) { PushbackReader reader = new PushbackReader(new StringReader( scanner.next())); int c = -1; while ((c = reader.read()) != -1) { // System.out.print((char) c + " "); if ((char) c != '(' && (char) c != ')' && !((char) c == '-' || ('0' <= (char) c && (char) c <= '9'))) { continue; } switch ((char) c) { case '(': if (f(reader)) { Val val = new Val(0); val.noNum = true; stack.add(val); } break; case ')': // start calc int a = 0; for (Val i : stack) { a += i.i; } Val val = null; if (!stack.empty()) { val = stack.pop(); } if (val != null && !val.notEnd && n == a && !val.noNum) { b = true; // break A; } if (stack.empty()) break A; break; default: StringBuilder builder = new StringBuilder(); builder.append((char) c); find(builder, reader, stack); } } } ; System.out.println(b ? "yes" : "no"); } while (scanner.hasNext()); } }

: