71. Simplify Path - Medium
前往題目
想法
stack
思路
這題不難,不過edge case
很多,要一次想出完美的條件判斷不容易
- 先用
/
分開 - 疊代分開後的每個部分
- 遇到
.
或是空的就跳過,因為不用做任何處理,直接忽略就好 - 遇到
..
就把上一個東西刪掉 - 其餘就都記錄下來
- 最後重新拼裝就好了
Code
class Solution {
public String simplifyPath(String path) {
String[] str = path.split("/"); // Split and store
Stack<String> stk = new Stack<String>();
for (String part : str) {
// ignore . and empty section
if (part.equals(".") || part.isEmpty()) continue;
// Pop when ..
if (part.equals("..")) {
if (!stk.isEmpty()) {
stk.pop();
}
continue;
}
// Push other elements
stk.push(part);
}
StringBuilder res = new StringBuilder();
while (!stk.isEmpty()) {
res.insert(0, "/" + stk.pop());
}
return res.length() == 0 ? "/" : res.toString();
}
}
71. Simplify Path - Medium
https://f88083.github.io/2024/08/16/71-Simplify-Path-Medium/