天天看點

HDU1022(堆棧應用)

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1022

代碼有點醜

package D0724;

import java.util.*;

public class HDU1022 {
	static String strIn;
	static String strOut;
	static Stack<Character> stackIn ;//儲存入站的順序
	static Stack<Character> stackOut;//接收出棧順序

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n;
		while (sc.hasNext()) {
			stackIn = new Stack<Character>();
			stackOut = new Stack<Character>();
			n = sc.nextInt();
			strIn = sc.next();
			strOut = sc.next();
			String result = getResult(n);
			if (result.equals("no"))
				System.out.println("No.");
			else {
				System.out.println("Yes.");
				result = result.trim();
				String[] str = result.split("\\ ");
				//注意不能是String[] str = result.split(" ");杭電好像不支援
				for (int i = 0; i < str.length; i++)
					if (!str.equals(" "))
						System.out.println(str[i]);
			}
			System.out.println("FINISH");
		}
	}

	private static String getResult(int n) {
		int i, j, k;
		String result = "";
		char top = strIn.charAt(0);// 棧頂指針
		// 初始化棧
		for (i = n - 1; i >= 0; i--) {
			char temp = strOut.charAt(i);
			stackOut.push(temp);
		}
//		先讓第一列車進站
		stackIn.push(strIn.charAt(0));
		result += " in";
		i = j = k = 1;
		while (!stackOut.isEmpty()) {
			char t = stackOut.pop();
			if (t == top) {
				result += " out";
				stackIn.pop();
				if (!stackIn.isEmpty())
					top = stackIn.peek();
			} else {
				for (i = j; i < n; i++) {
					if (strIn.charAt(i) == t) {
						// System.out.println(j+"- "+i);
						for (k = j; k <= i; k++) {
							stackIn.push(strIn.charAt(k));
							result += " in";
						}
						break;
					}
				}
				j = i + 1;
				if (i >= n) {
					result = "no";
					return result;
				}

				stackIn.pop();
				result += " out";
				if (!stackIn.isEmpty())
					top = stackIn.peek();

			}
		}
		return result;
	}
}