首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归地从映射中查找字符串的值

递归地从映射中查找字符串的值
EN

Stack Overflow用户
提问于 2015-01-22 12:47:37
回答 2查看 333关注 0票数 0

我有一个包含键和值<String, String>的hashmap。

即mapValue:

代码语言:javascript
复制
mapValue.put("A","B-7");
mapValue.put("B","START+18");
mapValue.put("C","A+25");

现在,我要计算'C'的表达式。因此,对于C,表达式将被(((START+18)-7)+25)替换。

因此,如果使用anymethod,我将传递字符串C,它应该返回字符串"(((START+18)-7)+25)",并且希望根据优先级对其进行计算。

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-22 13:54:52

通常,这类函数的逻辑(假设,您知道可能的操作和语法是严格的)可以如下所示:

代码语言:javascript
复制
public String eval(HashMap<String, String> mapValue, String variable) {
    //get expression to be evaluated
    String tmp = mapValue.get(variable); 
    // For each knwon operation
    for (String op : OPERATIONS) { 
        // split expression in operators in Array
        String[] vars = tmp.split("\\" + op); 
        // for each Element of splitted expr. Array
        for (int i = 0; i < vars.length; i++) { 
            //Check if Element is a valid key in HashMap
            if (mapValue.containsKey(vars[i])) { 
                //if it is replace element with result of iteration
                vars[i] = eval(mapValue, vars[i]); // DO ITERATION
            }
            //if Element is not a valid key in has do nothing
        }
        //Join splitted string with proper operator
        tmp = join(vars, op);
    }
    //return in parenthesis
    return "(" + tmp + ")";
}

'eval(mapValue,“C”)的结果是:

代码语言:javascript
复制
(((START+18)-7)+25)

一些简短的连接功能可以实现如下:

代码语言:javascript
复制
public String join(String[] arr, String d) {
    String result = arr[0];
    int i = 1;
    while (i < arr.length) {
        result += d + arr[i];
        i++;
    }
    return result;
}

上面提供的所有代码更多地是为了说明逻辑,因为应该使用一些异常处理、更好的字符串操作等等。

希望它能帮上忙

干杯!

票数 1
EN

Stack Overflow用户

发布于 2015-01-22 13:34:47

正如注释中提到的,如果递归太深,我不建议递归--它可能导致堆栈溢出--异常。

另外,我建议不要使用字符串方程。字符串的解析速度很慢,可能导致意外的结果(正如@rtruszk "START“包含变量”A“所提到的)。

我创建了一个示例作为我的建议:

代码语言:javascript
复制
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class X {

    static interface Expression {

    }

    static class Combination implements Expression {
        Expression[] values;

        public Combination(Expression... values) {
            this.values = values;
        }

        @Override
        public String toString() {
            return "?";
        }
    }

    static class Reference implements Expression {
        private String reference;

        public Reference(String reference) {
            this.reference = reference;
        }

        @Override
        public String toString() {
            return reference;
        }
    }

    static class Number implements Expression {
        private int value;

        public Number(int value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return ""+value;
        }
    }

    public static void main(String[] args) {

        Map<String, Expression> mapValue = new HashMap<>();

        mapValue.put("START", new Number(42));
        String x = "C";

        mapValue.put("A", new Combination(    new Reference("B"), new Number(-7)));
        mapValue.put("B", new Combination(new Reference("START"), new Number(+18)));
        mapValue.put("C", new Combination(    new Reference("A"), new Number(+25)));

        int result = 0;
        ArrayList<Expression> parts = new ArrayList<>();
        parts.add(mapValue.get(x));
        while (!parts.isEmpty()) {

            debuggingOutput(x, result, parts);

            Expression expression = parts.remove(0);
            if (expression instanceof Combination)
                parts.addAll(Arrays.asList(((Combination) expression).values));
            else if (expression instanceof Reference)
                parts.add(mapValue.get(((Reference) expression).reference));
            else if (expression instanceof Number)
                result += ((Number) expression).value;
        }
        System.out.println(result);
    }

    private static void debuggingOutput(String x, int result, ArrayList<Expression> parts) {
        System.out.print(x);
        System.out.print(" = ");
        System.out.print(result);
        for (Expression part : parts) {
            System.out.print(" + ");
            System.out.print(part);
        }
        System.out.println();
    }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28089194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档