Snap_Diff

题意大概是实现linux里面的diff的功能,给你两个文件,如果f1比f2多的,就打印“-someContent”, 如果是f2比f1多的,就打印“+someContent”

思路大概就是

对f2简历一个map,来记录每个line的

对于f1里面每一个line
  如果map里面不包含这个line
     打印"-line"
  否则
     把这条记录的计数减一
     如果减完是0
       就删除

如果map还有剩的,就打印出来“+line”

代码:

public void printDiff(List<String> f1, List<String> f2) {
    Map<String, Integer> counter = new HashMap<>();
    for(String line: f2) {
        if(counter.containsKey(line)) {
            counter.put(line, counter.get(line) + 1);
        } else {
            counter.put(line, 1);
        }
    }
    for(String line: f1) {
        if(!counter.containsKey(line)) {
            System.out.println("-" + line);
        } else {
            if(counter.get(line) == 0) {
                counter.remove(line);
            } else {
                counter.put(line, counter.get(line) - 1);
            }
        }
    }
    for(Map.Entry<String, Integer> entry: counter.entrySet()) {
        for(int i = 0; i < entry.getValue(); i++) {
            System.out.println("+" + entry.getKey());
        }
    }
}

public static void main(String[] args) {
    SnapDiff sample = new SnapDiff();
    List<String> f1 = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
    List<String> f2 = new ArrayList<>(Arrays.asList("A", "B", "D"));
    sample.printDiff(f1, f2);
}

results matching ""

    No results matching ""