標籤:
思路:先把路徑按反斜線split成數組,然後用一個ArrayList去類比。如果遇到空或者.則不處理;如果遇到..則刪除ArrayList最後一個元素(注意如果只有1個元素則不刪除);其他情況直接加到ArrayList裡面。注意特判輸入空串的情況。
1 import java.util.*; 2 public class Main { 3 public static void main(String[] args) { 4 Scanner cin = new Scanner(System.in); 5 int n = cin.nextInt(); 6 String curPath = cin.next(); 7 String[] curPathArr = curPath.split("/", -1); 8 cin.nextLine(); 9 while (n-- > 0) {10 String path = cin.nextLine();11 if (path.length() == 0)12 System.out.println(curPath);13 else {14 String[] pathArr = path.split("/", -1);15 ArrayList<String> resultArr = new ArrayList<String>();16 int st = 1;17 if (pathArr[0].length() == 0)18 resultArr.add("");19 else {20 for (String s : curPathArr)21 resultArr.add(s);22 st = 0;23 }24 for (int i = st; i < pathArr.length; i++) {25 if (pathArr[i].equals("..")) {26 if (resultArr.size() > 1)27 resultArr.remove(resultArr.size() - 1);28 }29 else if (!pathArr[i].equals(".") && !pathArr[i].equals(""))30 resultArr.add(pathArr[i]);31 }32 if (resultArr.size() == 1)33 System.out.println("/");34 else {35 for (int i = 0; i < resultArr.size() - 1; i++)36 System.out.print(resultArr.get(i) + "/");37 System.out.println(resultArr.get(resultArr.size() - 1));38 }39 }40 }41 }42 }
CCF2016.4 - C題