🍑 OJ专栏
🍑 HDOJ 1022 Train Problem Ⅰ
输入
3 123 321
3 123 312
输出
Yes.
in
in
in
out
out
out
FINISH
No.
FINISH
🍑 思路
🍤 栈顶元素与目标元素不匹配就进栈,匹配就出栈
🍤 匹配完:yes 源序列全进栈,栈顶不能匹配:no
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
int n = sc.nextInt();
String s1 = sc.next();
int i1 = 0;
int i2 = 0;
String s2 = sc.next();
Stack<Character> stack = new Stack<>();
ArrayList<String> list = new ArrayList<>();
stack.add('#');// 哨兵(保证栈不空)
while (!stack.isEmpty())
{
if (i2 == n)
break;
if (stack.peek() == s2.charAt(i2))
{
stack.pop();
list.add("out");
i2++;
} else
{
if (i1 == n)
break;
stack.add(s1.charAt(i1++));
list.add("in");
}
}
if (i2 == n && stack.peek() == '#')
{
System.out.println("Yes.");
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
} else
{
System.out.println("No.");
}
System.out.println("FINISH");
}
}
}