本文主要是介绍【专项刷题】— 栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、删除字符串中的所有相邻重复项 - 力扣(LeetCode)
思路:
- 使用栈进行操作,每次入栈的时候和栈顶元素进行比对,如果相同的话就弹出栈顶元素
- 也可以用数组来模拟栈进行操作
- 代码:
public String removeDuplicates(String s) {//转换成字符数组char[] ss = s.toCharArray();StringBuffer ret = new StringBuffer();for(char ch : ss){//当长度不为0且最后一个字符和要加入的字符相等的时候if(ret.length() > 0 && ret.charAt(ret.length()-1) == ch){//删除ret.deleteCharAt(ret.length() - 1);}else{//否则添加ret.append(ch);}}return ret.toString();}
2、基本计算器 II - 力扣(LeetCode)
思路:
代码:
public int calculate(String ss) {char[] s = ss.toCharArray();Deque<Integer> st = new ArrayDeque<>();int n = s.length;char op = '+';int i = 0;while(i < n){//排除空格if(s[i] == ' '){i++;}else if(s[i] >= '0' && s[i] <= '9'){int tmp = 0;while(i < n && s[i] >= '0' && s[i] <= '9'){//先更新数值tmp = tmp*10 + (s[i] - '0');i++;}//根据当前的操作符进行入栈if(op == '+'){st.push(tmp);}else if(op == '-'){st.push(-tmp);}else if(op == '*'){st.push(st.poll() * tmp);}else{st.push(st.poll() / tmp);}}else{//更新操作符op = s[i];i++;}}//出栈相加int ret = 0;while(!st.isEmpty()){ret += st.poll();}return ret;}
3、字符串解码 - 力扣(LeetCode)
思路:
代码:
public String decodeString(String ss) {char[] s = ss.toCharArray();int n = s.length;Stack<StringBuffer> str = new Stack<>();str.push(new StringBuffer());//先放一个空串Stack<Integer> nums = new Stack<>();int i = 0;while(i < n){if(s[i] >= '0' && s[i] <= '9'){int tmp = 0;while(i < n && s[i] >= '0' && s[i] <= '9'){tmp = tmp*10 + (s[i] - '0');i++;}nums.push(tmp);}else if(s[i] == '['){//先跳过 [ ,提取后面的字符i++;StringBuffer tmp = new StringBuffer();while(i < n && s[i] >= 'a' && s[i] <= 'z'){tmp.append(s[i]);i++;}str.push(tmp);}else if(s[i] == ']'){//开始解析,StringBuffer tmp = str.pop();int k = nums.pop();while(k-- != 0){str.peek().append(tmp);}i++;}else{//处理纯字符的情况,直接加到栈顶字符的后面StringBuffer tmp = new StringBuffer();while(i < n && s[i] >= 'a' && s[i] <= 'z'){tmp.append(s[i]);i++;}str.peek().append(tmp);}}return str.peek().toString();}
4、验证栈序列 - 力扣(LeetCode)
思路:
public boolean validateStackSequences(int[] pushed, int[] popped) {int j = 0;Deque<Integer> s = new ArrayDeque<>();//遍入栈的数组for(int x : pushed){//先入栈s.push(x);//如果栈顶与出栈顺序的数组相等while(!s.isEmpty() && s.peek() == popped[j]){s.pop();j++;}}return j == pushed.length;}
数组模拟栈:
public boolean validateStackSequences(int[] pushed, int[] popped) {int index = 0;int[] tmp = new int[pushed.length];for(int i = 0, j = 0; i < pushed.length; i++){tmp[index++] = pushed[i];while(index > 0 && tmp[index - 1] == popped[j]){index--;j++;}}return index == 0;}
这篇关于【专项刷题】— 栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!