Related: LeetCode 71 - Simplify Path
String cd(String origin, String path) ;Input: Origin (current directory), Path(a relative path)Output: Return destination path,Follow-up: what if path is an absolute path? just ignore origin to process path类似LC71
String cd(String origin, String path) ;Input: Origin (current directory), Path(a relative path)Output: Return destination path,Follow-up: what if path is an absolute path? just ignore origin to process path类似LC71
//O(n)
public static String commandCd(String origin,String path){
if(path==null||origin==null)return origin;
Stack<String> dir = new Stack<String>();
String o[] = origin.split("/");
for(String ss : o){
if(ss!=null&&ss.length()>0) dir.push(ss);
//You must control what store in stack
}
String p[] = path.split("/");
for(String c : p){
if(c.equals(".")||c.equals(""))continue;
else if(c.equals("..")&&!dir.isEmpty()) dir.pop();
else if(!c.equals("..")) dir.push(c);
}
//print out
StringBuilder sb = new StringBuilder(origin.length()+path.length());
if(dir.isEmpty())sb.append("/");
while(!dir.isEmpty()){
sb.insert(0,dir.pop());
sb.insert(0,"/");
}
return sb.toString();
}