HDU 1022 堆栈的应用

来源:互联网 发布:知乎 精华回答 编辑:程序博客网 时间:2024/06/05 11:32

题目大意:

堆栈的应用,较简单不说,贴出java 代码如下


注意:我刚开始提交的时候一直是 WA 不知道为什么,一直找不到原因, 算法思想一点都没错,改成 C++ 能 AC

在C++ 中用 while(cin>>X>>Y)  或者 c 用 scanf() != "EOF"  来判断是否到达 文件的末尾 ,而我一开始用  sc,nextInt() != -1 来判断, 不能通过 WA 用  sc.hasNext() 就能通过了,如果 已到文件的末尾则 抛出 NoSuchElementException - (如果输入信息已耗尽 ),[ 所以 在 PKU 上是 RunTimeErroe 错误)代码如下:

import java.util.ArrayList;import java.util.List;import java.util.Scanner;import java.util.Stack;public class HDU1022{Stack<Character> inStack = new Stack<Character>();Stack<Character> outStack = new Stack<Character>();String inStr = null;String outStr = null;List<Integer> re = new ArrayList<Integer>();int n =0;@SuppressWarnings("unused")private void solve(){boolean flage = false;Scanner sc = new Scanner(System.in);while (sc.hasNext()){n = sc.nextInt();flage = false;re.clear();inStack.clear();outStack.clear();inStr = sc.next();outStr = sc.next();//outStr for( int i=n-1;i>=0;i--){outStack.push(outStr.charAt(i));}// 求解for( int i=0;i<n;i++){inStack.push(inStr.charAt(i));re.add(1);// 放入while( !inStack.isEmpty() && !outStack.isEmpty() && inStack.peek() == outStack.peek()){re.add(0);// 移除出去inStack.pop();outStack.pop();}}if( inStack.isEmpty()){flage = true;}if( flage ){System.out.println("Yes.");}else{System.out.println("No.");System.out.println("FINISH");continue;}for(int i : re){if(i==1){System.out.println("in");}else{System.out.println("out");}}System.out.println("FINISH");}}public static void main(String[] args) {new HDU1022().solve();}}



原创粉丝点击