当前位置:编程学习 > JAVA >>

HDU1022(堆栈应用)

代码有点丑
[java] 
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(); 
 
            } 
        }  www.zzzyk.com

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,