天天看點

寫個Unix的diff指令的簡化版本

未完成。

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();
    }
}
           

繼續閱讀