题解 | #牛牛出入圈#
牛牛出入圈
https://www.nowcoder.com/practice/94b5c710f30c490f89be4f08b477edb4?tpId=363&tqId=10614533&ru=/exam/oj&qru=/ta/super-company23Year/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param enter int整型一维数组
* @param leave int整型一维数组
* @return bool布尔型
*/
public boolean validateCowCircle (int[] enter, int[] leave) {
Stack<Integer> stack = new Stack<>();
int index = 0;
for (int i = 0; i < enter.length; i++) {
stack.push(enter[i]);
while ((!stack.isEmpty()) && leave[index] == stack.peek()) {
stack.pop();
index++;
}
}
return stack.isEmpty();
}
}
本题知识点分析:
1.栈的出栈和入栈
2.数组遍历
3.数学模拟
本题解题思路分析:
1.每一个数组元素先push到栈中,如果此时栈不为空,并且栈顶元素和当前leave数组的数字相同,那么就pop出栈,然后index++
2.最后返回栈是否空即可,栈空,说明全部出栈成功
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞,支持一下,感谢~

