day11
1、leetcode20 有效的括号
-
思路
- 不匹配的情况
- 括号个数不匹配
- 若字符串长度为奇数,则直接返回flase
- 左括号多余
- 遍历完字符串,但栈不为空,说明存在有左括号无右括号进行匹配的情况,return false
- 右括号多余
- 遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号,return false
- 括号类型不匹配
- 遍历字符串匹配的过程中,发现栈里没有要匹配的字符。所以return false
- 括号个数不匹配
- 字符串遍历完之后,栈是空的,就说明全都匹配了。
- 不匹配的情况
-
tips:
- 在匹配左括号的时候,右括号先入栈,就只需要比较当前元素和栈顶相不相等就可以了
-
代码实现
class Solution { public boolean isValid(String s) { Stack<Character> st = new Stack<Character>(); char ch; if(s.length()%2 != 0) return false; for(int i=0; i<s.length(); i++){ ch = s.charAt(i); if(ch == '(') st.push(')'); else if(ch == '{') st.push('}'); else if(ch == '[') st.push(']'); //右括号多余、括号类型不匹配 else if(st.empty() || st.peek()!= ch ) return false; else st.pop(); } //左括号是否多余 return st.empty(); } }
2、leetcode1047 删除字符串中的所有相邻重复项
-
思路
- 遍历字符串,用栈来存放遍历过的元素
- 当遍历当前的这个元素的时候,去栈里看一下我们是不是遍历过相同数值的相邻元素,然后再去做对应的消除操作。
- 遍历字符串,用栈来存放遍历过的元素
-
代码实现
class Solution { public String removeDuplicates(String s) { Deque<Character> st = new LinkedList(); for(int i=0; i<s.length(); i++){ //若栈为空或当前遍历元素与栈顶元素不重复,则将该元素存入到栈中 if(st.isEmpty() || st.peekLast()!= s.charAt(i)){ st.addLast(s.charAt(i)); }else{//若栈顶元素和当前遍历元素重复,则从栈中弹出该元素 st.pollLast(); } } //将结果转换为字符串 String res = ""; while(!st.isEmpty()){ res = st.pollLast() + res;//注意字符串拼接顺序,若写出res+=st.pollLast(),则需反转字符串 } return res; } }
3、leetcode150 逆波兰表达式求值
-
逆波兰表达式(后缀表达式)
- 后缀表达式就是中缀表达式的二叉树形式的后序遍历(左右中)
- 计算机可以利用栈来顺序处理,不需要考虑优先级了。也不用回退了, 所以后缀表达式对计算机来说是非常友好的。
-
思路
- 创建一个数字栈
- 遍历字符串,遇到数字就将数字压入栈,遇到操作符就弹出两个数字进行运算,并将运算结果压入栈中
- 遍历结束后,栈中仅存的一个元素就是运算结果
-
代码实现
class Solution { public int evalRPN(String[] tokens) { Deque<Integer> st = new LinkedList(); for(int i=0; i<tokens.length; i++){ String s = tokens[i]; //遇到操作符就弹出两个数字进行运算,并将运算结果压入栈中,注意运算顺序 if("+".equals(s)){// leetcode 内置jdk的问题,不能使用==判断字符串是否相等 st.push(st.pop()+st.pop()); } else if("-".equals(s) ){ int num1 = st.pop(); int num2 = st.pop(); st.push(num2-num1); } else if("*".equals(s) ){ st.push(st.pop()*st.pop()); } else if("/".equals(s) ){ int num1 = st.pop(); int num2 = st.pop(); st.push(num2/num1); } else {//遇到数字就将数字压入栈 st.push(Integer.valueOf(s)); } } return st.pop(); } }

浙公网安备 33010602011771号