UTPC2011 C "\[\[iwi\]\]"

問題:http://atcoder.jp/problem/detail/27

コード

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		cs = s.next().toCharArray();
		System.out.println(f(0));
	}

	static char[] cs;
	static Deque<Integer> q = new ArrayDeque<Integer>();

	private static int f(int s) {
		if (s == cs.length + 1) {
			Integer[] is = q.toArray(new Integer[0]);
			int len = is.length - 1;
			if (len < 3 || len % 2 < 1) {
				return 0;
			}
			for (int i = 0; i < len / 2 - 1; ++i) {
				int a = is[i], b = is[len - i - 1];
				if (!(cs[a] == '(' && cs[b] == ')')
						&& !(cs[a] == ')' && cs[b] == '(')
						&& !(cs[a] == '{' && cs[b] == '}')
						&& !(cs[a] == '}' && cs[b] == '{')
						&& !(cs[a] == '[' && cs[b] == ']')
						&& !(cs[a] == ']' && cs[b] == '[')) {
					return 0;
				}
			}
			int j = len / 2;
			return cs[is[j - 1]] == 'i' && cs[is[j]] == 'w'
					&& cs[is[j + 1]] == 'i' ? len : 0;
		}
		int max = 0;
		for (int i = s; i <= cs.length; ++i) {
			q.add(i);
			max = Math.max(max, f(i + 1));
			q.removeLast();
		}
		return max;
	}
}