Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
corner case: "/a//b"
, ""
开始把/..
理解错了….
/a/b/.. = /a
, /../../../.. = /
public class Solution {
public String simplifyPath(String path) {
if(path.length()==0)return path;
String tokens[] = path.split("/");
Stack<String> stack = new Stack<String>();
for(int i=0;i<tokens.length;i++)
{
String s=tokens[i];
if(s.equals(".") || s.equals(""))continue;
if(s.equals(".."))
{
if(stack.size()>0)stack.pop();
}
else stack.push(s);
}
StringBuffer sb=new StringBuffer();
while(stack.size()>0)
{
sb.insert(0,stack.pop());
sb.insert(0,"/");
}
String s=sb.toString();
if(s.isEmpty())return "/";
else return s;
}
}