LeetCode-232,255,20,1047:
232.用栈实现队列
225.用队列实现栈
20.有效的括号
1047.删除字符串中的所有相邻重复项
第一题:
两个栈串联即可实现,类似这种实现类型的题目,在构造函数内再对需要用到的数据结构进行初始化/
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack();
stack2 = new Stack();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if(!stack2.isEmpty()){
return stack2.pop();
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
public int peek() {
if(!stack2.isEmpty()){
return stack2.peek();
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.peek();
}
}
public boolean empty() {
if(stack1.isEmpty() && stack2.isEmpty()){
return true;
}else{
return false;
}
}
}
用两个队列实现(感觉这个相比一个队列更难想。。。):
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int x) {
queue2.add(x);
while(!queue1.isEmpty()){
queue2.add(queue1.poll());
}
Queue<Integer> temp = queue2;
queue2 = queue1;
queue1 = temp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}
匹配并去重就需要优先想到使用栈:每放进去一个新的元素都需要进行判断
class Solution {
public boolean isValid(String s) {
char[] array = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (int i = 0; i <s.length(); i++) {
if(!stack.isEmpty()){
char temp = stack.peek();
if(temp == '[' && array[i] == ']'){
stack.pop();
} else if (temp == '(' && array[i] == ')') {
stack.pop();
} else if (temp == '{' && array[i] == '}'){
stack.pop();
}else {
stack.push(array[i]);
}
}else {
stack.push(array[i]);
}
}
if(stack.isEmpty()){
return true;
}else {
return false;
}
}
}
思考:和上一题思路一样
class Solution {
public String removeDuplicates(String s) {
char[] arr = s.toCharArray();
Stack<Character> stack = new Stack<>();
for(int i=0;i<arr.length;i++){
if(!stack.isEmpty()){
char a = stack.peek();
if(arr[i]==a){
stack.pop();
}else{
stack.push(arr[i]);
}
}else{
stack.push(arr[i]);
}
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}
其实不用StringBuilder也可以