堆
栈
Easy
155.Min stack
我的代码:
用的标准的数组表示的栈结构。
class MinStack {
private int N;
private int[] arr;
/** initialize your data structure here. */
public MinStack() {
N=0;
arr=new int[1];
}
public void push(int x) {
if(N==arr.length)
resize(2*arr.length);
arr[N++]=x;
}
public void pop() {
if(isEmpty()) return;//注意这边是return;不是return null
N--;
if(N==arr.length/4)
resize(arr.length/2);
}
public int top() {
return arr[N-1];
}
public int getMin() {
int k=N;
int min=0;
for(int i=1;i<k;i++){
if(arr[i]<arr[min])
min=i;
}
return arr[min];
}
public void resize(int len){
int[] temp=new int[len];
for(int i=0;i<N;i++){
temp[i]=arr[i];
}
arr=temp;
}
public boolean isEmpty(){
return size()==0;
}
public int size(){
return N;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
优解:
对于push和pop两次这部分代码,画个图,一眼明了。
[MAX,-2, 0, -2,-3 , 5, -3,-4]
package test;
import java.util.Stack;
public class Solution {
int min = Integer.MAX_VALUE;
Stack<Integer> stack = new Stack<Integer>();
public void push(int x) {
//仅在传入的x比min更小才会push两次,否则只会push一次 即 传入的x
if (x <= min) { //注意这边等号不能少,因为下面pop时发现=min,他会pop两次,因此我push也得对应搞两次。
stack.push(min); //这样保证了推入x之前推入的是目前为止第二小的值
min = x; //第一小的值是现在的x
}
stack.push(x);
}
public void pop() {
//如果发现pop的值和min一样,那么就会pop两次,并且把第二次pop的值赋给min,而第二次pop的值是倒数第二小的值
//因为最小的值和倒数第二小的值在插入的时候就是一起放进去的,连体婴儿。
if (stack.pop() == min) //至少会pop一次,发生在判断是否==min的时候
min = stack.pop();
}
public int top() { //画图可知,若pop两次,第二次正好把多放入的min给pop掉了,因此top()查看·到·的元素和正常插入的元素一样。
return stack.peek();
}
public int getMin() {
return min;
}
}
20. Valid Parentheses
优解:
package test;
import java.util.Stack;
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
if(s.length() % 2 == 1)
return false;//显然,符合题目要求的字符串必定是有偶数个字符
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')'); //存其相反的“符号”
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c) //按照题意,stack.pop()应该要=c
return false;
}
return stack.isEmpty(); //注意,这边stack.isEmpty()换成true是错的!!!
}
public static void main(String[] args) {
boolean flag=new Solution().isValid("(()[]{}");
System.out.println(flag);
}
}
注:
- 为什么return stack.isEmpty(); 不能替换成 return true。 因为"( ( ) [ ] {
}“这种情况下,不会中途return
false,但此时stack不为空,多了一个“)”,显然不是题目所要求的那样,但却会return true。 极端点,若换成
return true,”( ( ( ( ( ( ) [ ] { }"都会return true。 - else if (stack.isEmpty( ) || stack.pop( ) != c)中stack.isEmpty存在的必要性:
如果是这样子的情况,[ ]{ }( ) Z,我遍历完 ")"后,此时stack确实是空的。当我遍历到Z时,栈为空,表明我这个遍历到的元素必定不是三个括号类型以内的任意一个,那肯定就不符合题意了。因为[ ]{ }( ) )这种也是不满足题目要求的。因此若发现栈为空,可以直接认为这串字符不符合题意了。
优解2:
package test;
import java.util.Stack;
public class Solution {
public boolean isValid(String s) {
if (s.length() % 2 == 1)
return false;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') { // 字符串也可以不转化为数组的方法
stack.push(')');
} else if (s.charAt(i) == '{') {
stack.push('}');
} else if (s.charAt(i) == '[') {
stack.push(']');
} else if (stack.isEmpty() || stack.pop() != s.charAt(i))
return false;
}
return stack.isEmpty();
}
}
Medium
22. Generate Parentheses
思路:
也是递归的思想:
如果有人想知道为什么这样做,那么主要的概念是在圆括号平衡字符串中,在任意数量的前缀种,’ )‘的数量必须小于’( '。括号平衡字符串(大小为2*N)必须有N个“( ”和N个“ )”。我们继续为每个递归状态字符串添加在“ )”前添加“( ”,直到“( ”的计数等于N。然后我们开始添加“ )”。
代码:
package test;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
backtrack(list, "", 0, 0, n);
return list;
}
public void backtrack(List<String> list, String str, int open, int close, int max){
if(str.length() == max*2){ //让整个递归结束的语句,即长度满6就结束了
list.add(str);
return;
}
if(open < max) //至少一次,至多三次
backtrack(list, str+"(", open+1, close, max);
if(close < open)//至少一次,至多三次,但因为在下面,所以他的次数肯定小于等于上面语句执行的次数
backtrack(list, str+")", open, close+1, max);
}
public static void main(String[] args) {
List<String> list=new Solution().generateParenthesis(3);
for(String s:list) {
System.out.println(s);
}
}
}