【问题标题】:find sequence in the hashmap在哈希图中查找序列
【发布时间】:2015-01-13 08:06:32
【问题描述】:

我有一个表示 [from, to] 的 hashmap:

1st: [start->sb1]
2nd: [sb0->sb3]
3rd: [sb1->sb0]
4th: [sb3->end]

我想知道是否有办法找到正确的序列,例如:

start->sb1->sb0->sb3->end

【问题讨论】:

  • 当然,有办法。你试过什么?

标签: java sorting hashmap sequence


【解决方案1】:

如果你知道start 键,那就很简单了:

String key = "start";
while (key != null && !key.equals("end")) {
    System.out.print(key + "->");
    key = map.get(key);
}
if (key != null)
    System.out.println(key);

这假设地图的键和值是字符串。

【讨论】:

    【解决方案2】:

    简单的递归就可以解决问题:

    public static void main(String... args) {
        Map<String, String> path = new HashMap<>();
        path.put("start", "sb1");
        path.put("sb0", "sb3");
        path.put("sb1", "sb0");
        path.put("sb3", "end");
    
        printPath(path, "start");
    }
    
    void printPath(Map<String, String> path, String next) {
        if (next != null) {
            System.out.print(next);
            printPath(path, path.get(next));
        }
    }
    

    这个 impl 简单地打印 System.out 上的所有条目。我假设您宁愿将它们收集在 List 或类似的地方,如果它们稍后将在程序中使用。

    List<String> result = new ArrayList<>();
    buildPath(path, "start", result);
    
    void buildPath(Map<String, String> path, String token, List<String> result) {
        if (token != null) {
            result.add(token);
            buildPath(path, path.get(token), result);
        }
    }
    

    【讨论】:

    • 是否可以使用 com.google.common.collect.Multimap 调整您的示例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多