题目1:【二刷完成】
代码1:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char ch;
for (int i=0; i<s.length(); i++){
ch = s.charAt(i);
if (ch=='('){
stack.push(')');
}else if (ch=='['){
stack.push(']');
}else if (ch=='{'){
stack.push('}');
}else if (stack.empty() || stack.peek()!=ch){
return false;
}else{
stack.pop();
}
}
return stack.empty();
}
}
题目2:【二刷完成】
代码2:
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
char ch1 ;
String newS = new String();
for (int i=0; i<s.length();i++){
ch1 = s.charAt(i);
if (stack.empty() || ch1 != stack.peek()){
stack.push(ch1);
}else{
stack.pop();
}
}
while(!stack.empty()){
newS = stack.pop() + newS;
}
return newS;
}
}
题目3:【二刷完成】
代码3:
lass Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String i : tokens){
if ("+".equals(i)){
stack.push(stack.pop() + stack.pop());
}else if ("/".equals(i)){
int a=stack.pop();
int b=stack.pop();
stack.push(b/a);
}else if ("*".equals(i)){
stack.push(stack.pop() * stack.pop());
}else if ("-".equals(i)){
stack.push(-stack.pop() + stack.pop());
}else{
stack.push(Integer.valueOf(i));
}
}
return stack.pop();
}
}
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(int i=0;i<tokens.length;i++){
if ("+".equals(tokens[i])){
stack.push(stack.pop()+stack.pop());
}else if ("-".equals(tokens[i])){
int num = stack.pop();
stack.push(stack.pop()-num);
}else if ("*".equals(tokens[i])){
stack.push(stack.pop()*stack.pop());
}else if ("/".equals(tokens[i])){
int num = stack.pop();
stack.push(stack.pop()/num);
}else{
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}