题目

结果
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { public String simplifyPath(String path) { List<String> list = new ArrayList<>(); path = removeDuplicateSlash(path);
String[] paths = path.split("/"); for (String str : paths) { if (str.isBlank()) { continue; } if (str.equals(".")) { continue; } if (str.equals("..")) { if (!list.isEmpty()) { list.remove(list.size() - 1); } continue; } list.add(str); }
StringBuilder ans = new StringBuilder("/"); for (String str : list) { ans.append(str).append("/"); } return removeLastSlash(ans.toString()); }
private String removeLastSlash(String path) { if (path.length() != 1 && path.endsWith("/")) { return path.substring(0, path.length() - 1); } return path; }
private String removeDuplicateSlash(String path) { return path.replaceAll("//+", "/"); } }
|
复杂度
时间复杂度:O(?),replaceAll和substring的复杂度不太清楚
空间复杂度:O(n)