Straight forward solution with a tiny bit of Java8


  • 9

    If the creation of the map can also be done using Java8 that would have been cool.

    public static List<List<String>> findDuplicate(String[] paths) {
            Map<String, List<String>> map = new HashMap<>();
            for(String path : paths) {
                String[] tokens = path.split(" ");
                for(int i = 1; i < tokens.length; i++) {
                    String file = tokens[i].substring(0, tokens[i].indexOf('('));
                    String content = tokens[i].substring(tokens[i].indexOf('(') + 1, tokens[i].indexOf(')'));
                    map.putIfAbsent(content, new ArrayList<>());
                    map.get(content).add(tokens[0] + "/" + file);
                }
            }
            return map.values().stream().filter(e -> e.size() > 1).collect(Collectors.toList());
        }
    

  • 0

    Clear and straightforward solution.
    A small suggestion though, we can get the tokens[0] before the second loop, so that we don't have to access it every time in inner loop.

           ...
           for (String path : paths) {
                String[] tokens = path.split(" ");
                String prefix = tokens[0];
                for (int i = 1; i < tokens.length; i++) {
                    ...
                    map.get(content).add(prefix + "/" + file);
                }
            }
           ...
    

  • 0

    @dilyar thanks for the suggestion, Is there a difference between accessing tokens[0] directly or storing it in a prefix variable and accessing prefix in the inner loop ?


  • 0

    @johnyrufus16

    Realized you dont need the key, so we can directly create the stream on values, hence changed from

    return map.entrySet().stream().filter(e -> e.getValue().size() > 1).map(e -> e.getValue()).collect(Collectors.toList());
    

    to

    return map.values().stream().filter(e -> e.size() > 1).collect(Collectors.toList());
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.