栈
import java.util.Stack;
class Solution {
public String simplifyPath(String path) {
/**
* 如果有连续的"//"会变成空字符串,需要额外判断
*/
String[] newString = path.split("/");
Stack<String> stack = new Stack<>();
for (int i = 0; i < newString.length; i++) {
String string = newString[i];
/**
* 额外判断空字符串
*/
if (string.equals(".") || string.equals("")){
continue;
}
else if (string.equals("..")){
/**
* 如果是根目录则不能返回上一级
*/
if (!stack.isEmpty()) {
stack.pop();
}
else {
continue;
}
}
else {
stack.push(string);
}
}
/**
* 栈空了则返回"/"
*/
if (stack.isEmpty()){
return "/";
}
/**
* 栈是以逆序弹出,因此用另一个栈来存储,再正序弹出
*/
StringBuilder str = new StringBuilder();
Stack<String> temp = new Stack<>();
while (!stack.isEmpty()){
temp.push(stack.pop());
}
while (!temp.isEmpty()){
str.append("/");
str.append(temp.pop());
}
return str.toString();
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/simplify-path/