CCF認證201604-3 路徑解析
阿新 • • 發佈:2018-12-17
依舊是java 90分 已經不知道錯誤
過路的大神知道錯誤請指出
思路:
這道題參考了網上的部落格,思路是先把路徑合併,然後消掉不規範的路徑即可。
一開始腦子抽了,以為要構建連結串列,我也不知道怎麼想的。
程式碼:
// java import java.util.Scanner; public class Main{ private static Scanner cin; public static void main(String[] args) { cin = new Scanner(System.in); int n = cin.nextInt(); String local = cin.next(); if(local.charAt(local.length()-1) != '/') local = local + "/"; // System.out.println("local = " + local); while (n-->0){ String path = cin.next(); if(path.charAt(0) != '/') path = local + path; // 刪掉多個/// while (path.contains("//")){ path = path.replaceAll("//","/"); } // 刪掉 ./ while(path.contains("/./")) path = path.replaceAll("/./","/"); // 處理 /../的情況 while (path.contains("/../")){ int pos = path.indexOf("/../"); if(pos == 0){ // 根目錄下的 path = path.substring(3); }else{ int npos = path.lastIndexOf("/",pos-1); // System.out.println(path); // System.out.println("substr: "+ path.substring(npos,pos+3)); // System.out.println("npos: " + npos + " pos " + (pos+3) ); // substring 不取尾! path = path.replaceAll(path.substring(npos,pos+4),"/"); } } int len = path.length(); if( len > 1 && path.charAt(len-1)=='/'){ path = path.substring(0,len-1); } System.out.println(path); } } } // c++ #include <iostream> #include <string> using namespace std; int main(){ int num; string curDir; cin >> num >> curDir; getchar(); for (int i = 0; i<num; i++){ string line; getline(cin, line); int pos; // 添加當前目錄 if (line[0] != '/'){ line = curDir + "/" + line; } if (line.size() == 0){ line = curDir; } // 除去多個/// while ((pos = line.find("//")) != -1){ int count = 2; while (line[pos + count] == '/'){ count++; } line.erase(pos, count - 1); } // 除去../ while ((pos = line.find("/../")) != -1){ if (pos == 0){ line.erase(pos + 1, 3); } else{ int spos; spos = line.rfind("/", pos - 1); line.erase(spos, pos - spos + 3); } } // 除去./ while ((pos = line.find("/./")) != -1){ line.erase(pos + 1, 2); } // 除去最後一個/ if (line.size()>1 && line[line.size() - 1] == '/') line.erase(line.size() - 1); cout << line << endl; } return 0; }