题目链接
题目:给出两个数组,调整第一个数组的输入输出顺序能否变成第二个数组
示例:
输入: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出: true
思路:遍历一下,利用栈的属性
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<Integer>();
int k = popped.length;
int j = 0;
if(k == 0){
return true;
}
for(int i = 0; i < k; i++){
if(popped[j] == pushed[i]){
j++;
}else if(stack.isEmpty()){
stack.push(pushed[i]);
}else{
if(stack.peek() == popped[j]){
stack.pop();
j++;
i--;
}else{
stack.push(pushed[i]);
}
}
}
while(!stack.isEmpty() && stack.peek() == popped[j]){
stack.pop();
j++;
}
if(stack.isEmpty() && j == k){
return true;
}
return false;
}
}
我的代码有点low,看看别人的代码 不过他的代码没我的快点 哈哈哈
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<Integer>();
int i = 0;
for(int x : pushed){
stack.push(x);
while(!stack.isEmpty() && stack.peek() == popped[i]){
stack.pop();
i++;
}
}
return i == popped.length;
}
}