思路:先把路径按反斜杠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 }
时间: 2024-10-12 17:14:14