Java栈常用操作及相关leetcode算法题

Java栈常用操作

1、创建栈

Stack<Integer> stack = new Stack<>();

stack.push(1);
stack.push(2);
stack.push(3);

3、获取栈顶元素

int top = stack.peek();

4、删除栈顶元素

int top = stack.pop();

5、获取栈的长度

int length = stack.size();

6、判断栈是否为空

boolean isEmpty = stack.isEmpty();

7、栈的遍历

while(!stack.isEmpty()) {
int top = stack.pop();
}

8、栈相关leetcode

No.20 有效的括号

class Solution {
public boolean isValid(String s) {
if(s.length() == 0)
return true;
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()) {
if(c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if(stack.isEmpty())
return false;
if(c == ')') {
char top = stack.pop();
if(top != '(')
return false;
}
if(c == ']') {
char top = stack.pop();
if(top != '[')
return false;
}
if(c == '}') {
char top = stack.pop();
if(top != '{')
return false;
}
}
}
if(!stack.isEmpty())
return false;
return true;
}
}


No.496 下一个更大的元素

class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
ArrayList<Integer> result = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
Stack<Integer> temp = new Stack<>();
for(int i = 0; i < nums2.length; i++) {
stack.push(nums2[i]);
}
for(int i = 0; i < nums1.length; i++) {
int max = -1;
boolean isFound = false;
while(!stack.isEmpty() && !isFound) {
int top = stack.pop();
temp.push(top);
if(top > nums1[i])
max = top;
if(top == nums1[i]) {
isFound = true;
}
}
if(isFound)
result.set(i, max);
while(!temp.isEmpty()) {
int top = temp.pop();
stack.push(top);
}
}
return result.stream().mapToInt(k->k).toArray();
}
}


class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
ArrayList<Integer> result = new ArrayList<>();
if(nums1 == null || nums1.length == 0)
return nums1;
for(int i = 0; i < nums1.length; i++) {
int max = -1;
boolean isFound = false;
for(int j = nums2.length - 1; j >= 0 && !isFound; j--) {
if(nums2[j] == nums1[i]) {
isFound = true;
}
if(nums2[j] > nums1[i])
max = nums2[j];
}
if(isFound)
result.set(i, max);
}
return result.stream().mapToInt(k->k).toArray();
}
}


06-17 1万+

01-25 3111
04-03 2506
05-15 870
08-16 337
05-04 3万+
03-30 2033
01-10 54