题意:简化路径。
思路:构建两个栈stack和temp。对于一个字符串,遇到“.”或者空的时候,不作处理;遇到“..”的时候,stack就弹出;其他就直接入栈。
输出的时候,先把stack栈出栈,temp再入栈。
代码:
public class SimplifyPath {
public String Simplify(String path) {
if(path == null || path.length() == 0) return null;
Stack<String> stack = new Stack<>();
String []str = path.split("/");
for(int i = 0 ; i < str.length ; i++){
if(str[i].equals(".") || str.length) == 0) continue;
else if(!stack.isEmpty()){
if(str[i].equals("..")){
stack.pop();
}else
stack.push(str[i]);
}
StringBulider sb = new StringBulider)();
Stack <String> temp = new Stack<>();
while(!stack.isEmpty()){
temp.push(stack.pop());
}
while(!temp.isEmpty()){
sb.append("/"+temp.pop());
}
if(sb.length == 0 ) sb.append("/");
return sb.toString();
}
本文介绍了一种简化路径的算法实现,通过使用两个栈来处理输入的路径字符串,有效地实现了路径的规范化。具体步骤包括解析路径字符串、处理特殊字符并最终生成规范化的路径。
843

被折叠的 条评论
为什么被折叠?



