力扣算法学习day07-2
225-用队列实现栈
题目
代码实现
class MyStack {
// 造一个队列
Queue<Integer> queue = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
// 方法一:
// queue.offer(x);
// 方法二:
// 312
if(queue.isEmpty()){
queue.offer(x);
return;
}
int i = queue.size();
queue.offer(x);
while(i > 0){
queue.offer(queue.poll());
i--;
}
}
public int pop() {
// 方法一:
// int i = queue.size();
// while(i > 1){
// queue.offer(queue.poll());
// i--;
// }
// return queue.poll();
// 方法二:
return queue.poll();
}
public int top() {
// 方法一:
// int i = pop();
// queue.offer(i);
// return i;
// 方法二:
return queue.peek();
}
public boolean empty() {
// 方法一、二相同。
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
20-有效的括号
题目
代码实现
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char[] sChar = s.toCharArray();
int i = 0;
while(i < sChar.length){
switch(sChar[i]){
case '(':
stack.push(')');
break;
case '{':
stack.push('}');
break;
case '[':
stack.push(']');
break;
case ')':
if(stack.empty() || stack.pop() != ')'){
return false;
}
break;
case '}':
if(stack.empty() || stack.pop() != '}'){
return false;
}
break;
case ']':
if(stack.empty() || stack.pop() != ']'){
return false;
}
break;
}
i++;
}
return stack.empty();
}
}