力扣笔记之栈与队列常见题型

记录刷力扣时遇到的一些技巧(栈与队列)
简单的逆波兰表达式
计算器无括号有乘除后缀表达式

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stk = new Stack<Integer>();
        for(String token : tokens){
            if(token.equals("+")) stk.push(stk.pop()+stk.pop());
            else if(token.equals("-")) stk.push(-stk.pop()+stk.pop());
            else if(token.equals("*")) stk.push(stk.pop()*stk.pop());
            else if(token.equals("/")) 
            {
                int a=stk.pop(),b=stk.pop();
                stk.push(b/a);
            }
            else stk.push(Integer.parseInt(token));
        }
        return stk.pop();
    }
}

[227]给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

整数除法仅保留整数部分。
计算器无括号有乘除

class Solution {
    public int calculate(String s) {
        // 保存上一个符号,初始为 +
        char sign = '+';
        Stack<Integer> numStack = new Stack<>();
        // 保存当前数字,如:12是两个字符,需要进位累加
        int num = 0;
        int result = 0;
        for(int i = 0; i < s.length(); i++){
            char cur = s.charAt(i);
            if(cur >= '0'){
                // 记录当前数字。先减,防溢出
                num = num*10 - '0' + cur;
            }
            if((cur < '0' && cur !=' ' )|| i == s.length()-1){
                // 判断上一个符号是什么
                switch(sign){
                    // 当前符号前的数字直接压栈
                    case '+': numStack.push(num);break;
                    // 当前符号前的数字取反压栈
                    case '-': numStack.push(-num);break;
                    // 数字栈栈顶数字出栈,与当前符号前的数字相乘,结果值压栈
                    case '*': numStack.push(numStack.pop()*num);break;
                    // 数字栈栈顶数字出栈,除于当前符号前的数字,结果值压栈
                    case '/': numStack.push(numStack.pop()/num);break;
                }
                // 记录当前符号
                sign = cur;
                // 数字清零
                num = 0;
            }
        }
        // 将栈内剩余数字累加,即为结果
        while(!numStack.isEmpty()){
            result += numStack.pop();
        }
        return result;
    }
}

计算器有括号无乘除

class Solution {
    public int calculate(String s) {
        Stack<Integer> stack =new  Stack<Integer>();
        int sign = 1,res = 0;
        int length = s.length();
        for(int i=0;i<length;i++){
            char ch = s.charAt(i);
            if(Character.isDigit(ch)){
                int cur = ch - '0';
                //多位数字
                while(i+1<length&& Character.isDigit(s.charAt(i+1))){
                    i++;
                    int a =s.charAt(i)-'0';
                    cur = cur*10 + a ;
                }
                res += sign*cur;
            }
            else if(ch == '+') sign=1;
            else if(ch == '-') sign=-1;
            //存历史数据
            else if(ch == '(') {
                stack.push(res);
                stack.push(sign);
                res = 0;
                sign = 1;
            } 
            else if(ch == ')') res = stack.pop() * res + stack.pop();
         }
         return res;
        }
    }

有括号有乘除

public int solve (String s) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        int number = 0;
        int sum = 0;
        char sign = '+';
        char[] c = s.toCharArray();
        int n = s.length();
        for (int i = 0; i < n; i++)
        {
            char ele = c[i];
            //process the numerical situation
            if (Character.isDigit(ele))
            {
                number = number * 10 + ele - '0';
            }
            //process the () situation
            if (ele == '(')
            {
                int j = i + 1;
                int counterPar = 1;
                String subPar = "";
                //extract the most outer group and recursevely preocess
                while (counterPar > 0)
                {
                    if (c[j] == '(')
                    {
                        counterPar++;
                    }
                    if (c[j] == ')')
                    {
                        counterPar--;
                    }
                    j++;
                }
                subPar = s.substring(i + 1, j);
                number=solve(subPar);
                i = j-1;
            }
            //real work block
            if (ele != ' ' && !Character.isDigit(ele) || i == n - 1)
            {
                if (sign == '+')
                {
                    stack.push(number);
                }
                else if (sign == '-')
                {
                    stack.push(-1 * number);
                }
                else if (sign == '*')
                {
                    stack.push(stack.pop() * number);
                }
                else if (sign == '/')
                {
                    stack.push(stack.pop() / number);
                }
                //change the sign and number
                number = 0;
                sign = ele;
            }
 
        }
        while (!stack.isEmpty())
        {
            sum+=stack.pop();
        }
        return sum;
    }

[32]给你一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

class Solution {
    public int longestValidParentheses(String s) {
    	int max=0;//存放最大的长度
    	int len=s.length();//字符串长度
    	Stack<Integer> stack=new Stack<Integer>();//暂存字符
    	stack.push(-1);//初始化栈底
    	for(int i=0;i<len;i++) {//遍历字符串
    		if(s.charAt(i)=='(')//字符串存在(
    			stack.push(i);//下标入栈
    		else {//只有右边
    			stack.pop();//下标出栈
    			if(stack.isEmpty()) {//出栈以后,栈为空
    				stack.push(i);//让当前下标进栈
    			}else {//不为空,就计算长度差值
    				max=Math.max(max, i-stack.peek());//选出最长的长度
    			}
    		}
    	}
    	return max;
    }
}

给出一个仅包含字符’(’,’)’,’{’,’}’,’[‘和’]’,的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()“和”()[]{}“都是合法的括号序列,但”(]“和”([)]"不合法。

public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        //使用foreach循环
        for (char c : s.toCharArray()) {
            if (c == '(')
                stack.push(')');
            else if (c == '{')
                stack.push('}');
            else if (c == '[')
                stack.push(']');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        return stack.isEmpty();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值