今天是第十一天,继续更深入的学习栈和队列
class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(char c: s.toCharArray()){ if(c == '('){ stack.push(')'); } else if(c == '{'){ stack.push('}'); } else if(c == '['){ stack.push(']'); } else{ if(stack.isEmpty()||c!=stack.pop()){ return false; } } } return stack.isEmpty(); } }
用stack是为了确认各种括号的顺序是符合规范的
class Solution { public String removeDuplicates(String s) { Stack<Character> stack = new Stack<>(); for(char c:s.toCharArray()){ if(stack.isEmpty()||c != stack.peek() ){ stack.push(c); } else{ stack.pop(); } } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()){ sb.append(stack.pop()); } return sb.reverse().toString(); } }
删除相邻重复的元素,push进相邻不同的,再把剩余的值返回
class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<>(); for (String s : tokens) { if ("+".equals(s)) { stack.push(stack.pop() + stack.pop()); } else if ("-".equals(s)) { stack.push(-stack.pop() + stack.pop()); } else if ("*".equals(s)) { stack.push(stack.pop() * stack.pop()); } else if ("/".equals(s)) { int temp1 = stack.pop(); int temp2 = stack.pop(); stack.push(temp2 / temp1); } else { stack.push(Integer.valueOf(s)); } } return stack.pop(); } }
就是根据符号来放入对应的值
今天的题都是stack相关,倒是不难,明天应该是queue了,加油
标签:第十一天,String,随想录,pop,else,push,求值,Stack,stack From: https://www.cnblogs.com/catSoda/p/16815228.html