20. 有效的括号
问题描述:
?代码:
class Solution {
public boolean isValid(String s) {
char []ss = new char[s.length()];
ss=s.toCharArray();
Map<Character,Character> hx = new HashMap<>();
hx.put(')','(');
hx.put(']','[');
hx.put('}','{');
Deque<Character> deque = new LinkedList<>();
for(int i=0;i<ss.length;i++){
if(hx.containsKey(ss[i])){
if(deque.isEmpty()||hx.get(ss[i])!=deque.peek())
return false;
deque.poll();
}else{
deque.push(ss[i]);
}
}
return deque.isEmpty();
}
}
思路:
?232. 用栈实现队列
问题描述:
?代码:
class MyQueue {
Deque<Integer> s1;
Deque<Integer> s2;
public MyQueue() {
s1= new LinkedList<Integer>();
s2 = new LinkedList<Integer>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
int front=s2.pop();
return front;
}
public int peek() {
if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
int front=s2.peek();
return front;
}
public boolean empty() {
if(s1.isEmpty()&&s2.isEmpty()){
return true;
}
return false;
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
思路:
利用堆栈和队列的性质
|