还原Stack操作

时间:2023-03-10 07:24:44
还原Stack操作

下午看到一题。给定两个int[]数组,int[] org和int[] res, 分别代表一串数字,和这串数字经过stack的push 和 pop操作之后的数字,让返回一个String, String里是stack操作的顺序, 比如 push 1, pop 1, push 2, pop 2等等。

假定没有重复数字,那么我们可以先建立一个栈,然后将org中的数字放入栈中,再用栈顶元素和结果数组中的数字进行对比,来得出什么时候push或者pop。

大概代码如下:

import java.util.Stack;

public class Solution {

    public String getStackActions(int[] org, int[] res) {
if (org == null || res == null || org.length != res.length) return "";
Stack<Integer> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
int i = 0, j = 0;
int len = org.length; while (i < len) {
if (stack.isEmpty() || stack.peek() != res[j]) {
stack.push(org[i]);
sb.append("Push: " + org[i]).append("|");
i++;
} else {
int x = stack.pop();
sb.append("Pop: " + x).append("|");
j++;
}
} while (!stack.isEmpty()) {
int x = stack.pop();
sb.append("Pop: " + x).append("|");
}
sb.setLength(sb.length() - 1);
return sb.toString();
}
}

Test Client:

public class Program {

    public static void main(String[] args) {
// TODO Auto-generated method stub
int[] org = {1, 2, 3, 4, 5};
int[] res = {1, 2, 4, 5, 3};
Solution sol = new Solution();
String result = sol.getStackActions(org, res);
System.out.println(result); } }