写个Unix的diff命令的简化版本

来源:互联网 发布:网络渗透 视频 编辑:程序博客网 时间:2024/06/14 01:03

未完成。

class Solution {    public static String diff(String file1, String file2) {        StringBuffer sb = null;        try {            BufferedReader br1 = new BufferedReader(new FileReader(file1));            String inString = null;            HashMap<String, ArrayList<Integer>> firstMap = new HashMap<>();            int i = 0;            ArrayList<String> lines1 = new ArrayList<>();            ArrayList<String> lines2 = new ArrayList<>();            while((inString = br1.readLine()) != null) {                if(!firstMap.containsKey(inString))                     firstMap.put(inString, new ArrayList());                firstMap.get(inString).add(i);                i++;                lines1.add(inString);            }            BufferedReader br2 = new BufferedReader(new FileReader(file2));            while((inString = br2.readLine()) != null) {                lines2.add(inString);            }            HashMap<Integer, Integer> overlap = new HashMap<>();            HashMap<Integer, Integer> _overlap = new HashMap<>();            int subStartFirst = 0;            int subStartSecond = 0;            int maxOverlap = 0;            for (int j = 0; j < lines2.size(); j++) {                 String key = lines2.get(j);                if(firstMap.containsKey(key)) {                    for(int index : firstMap.get(key)) {                        int exist = 0;                        if(overlap.containsKey(index - 1))                            exist = overlap.get(index - 1);                        int update = ((index == 0 || exist == 0) ? 0 : exist) + 1;                        _overlap.put(index, update);                        if(update > maxOverlap) {                            maxOverlap = update;                            subStartFirst = index - maxOverlap + 1;                            subStartSecond = j - maxOverlap + 1;                        }                    }                }                overlap.clear();                overlap.putAll(_overlap);                _overlap.clear();            }            sb = new StringBuffer();            if(maxOverlap == 0) {                if(lines1.size() == 0) {                    sb.append("0a1," + lines2.size() + "\n");                    for(String s : lines2) {                        sb.append("> " + s + "\n");                    }                } else {                    sb.append("[");                  }            }        } catch (IOException ex) {            ex.printStackTrace();        }        return sb.toString();    }}


0 0
原创粉丝点击