package leetcode;
import java.util.Stack;
public class demo_71 {
public String simplifyPath(String path) {
String[] str=path.split("/");
Stack<String> stack=new Stack<String>();
Stack<String> sta=new Stack<String>();
//把地址按"/"进行分割,然后存入一个栈中
for(String s:str) {
//防止空栈
if(stack.empty()) {
stack.push("/");
}
//分割后的空格和"."都舍弃
if(s.equals(".")||s.equals("")) {
continue;
}
//如果是回退,则弹出顶层
if(s.equals("..")) {
stack.pop();
}
//否则存入栈中
else {
stack.push(s);
}
}
path="";
//存入栈的地址是相反的,所以存入另外一个栈进行修正
while(!stack.empty()) {
sta.push(stack.pop());
}
if(!sta.empty()&&sta.peek().equals("/")) {
sta.pop();
}
while(!sta.empty()) {
path=path+"/"+sta.pop();
}
if(path.equals("")) {path=path+"/";}
System.out.println(path);
return path;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
demo_71 d71=new demo_71();
String path="///a/./b/../../c/";
d71.simplifyPath(path);
}
}