码迷,mamicode.com
首页 > 其他好文 > 详细

241. 为运算表达式设计优先级

时间:2019-06-14 00:41:48      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:diff   运算优先级   new   运算符   string   inpu   class   hashmap   parent   

241. 为运算表达式设计优先级

题目描述

给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。

示例 1:

输入: "2-1-1"
输出: [0, 2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2

示例 2:

输入: "23-45"
输出: [-34, -14, -10, -10, 10]
解释:
(2(3-(45))) = -34
((23)-(45)) = -14
((2(3-4))5) = -10
(2((3-4)5)) = -10
(((23)-4)5) = 10

贴出代码

class Solution {
    private Map<String,List<Integer>> map = new HashMap<>();
    
    public List<Integer> diffWaysToCompute(String input) {
        
        if(map.containsKey(input)) 
            return map.get(input);
        
        List<Integer> res = new ArrayList<>();
        for(int i = 0; i < input.length(); i++){
            char c = input.charAt(i);
            if(c == '+' || c == '-' || c == '*'){
                List<Integer> left = diffWaysToCompute(input.substring(0,i));
                List<Integer> right = diffWaysToCompute(input.substring(i + 1,input.length()));
                for(int l : left){
                    for(int r : right){
                        if(c == '+'){
                            res.add(l + r);
                        }
                        if(c == '-'){
                            res.add(l - r);
                        }
                        if(c == '*'){
                            res.add(l * r);
                        }
                    }
                }
            }
        }
        if(res.size() == 0){
            res.add(Integer.parseInt(input));
        }
        map.put(input,res);
        return res;
    }
}

241. 为运算表达式设计优先级

标签:diff   运算优先级   new   运算符   string   inpu   class   hashmap   parent   

原文地址:https://www.cnblogs.com/Tu9oh0st/p/11020477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!