Find Directory Destination

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Find Directory Destination相关的知识,希望对你有一定的参考价值。

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

 

//General idea: split the path with "/" and then put them into the stack, when handling the origin path, split it and put it into the stack or choose to pop the content in the stack, finally, give the output.

public static String absolutePath(String origin, String path) {
  if (path.length() == 0) return origin;
  if (origin.length() == 0) return path;
  Stack<String> stack = new Stack<String>();
  String[] string = path.split("/");
  for (String s : string) {
    stack.push(s);
  }
  String[] str = origin.split("/");
  for (String s : str) {
    if (s.equals("") || s.equals(".")) continue;
    else if (s.equals("..") && !stack.isEmpty()) {
      stack.pop();
    } else {
      stack.push(s);
    }
  }
  StringBuilder result = new StringBuilder();
  while (!stack.isEmpty()) {
    result.insert(0, stack.pop());
    result.insert(0, "/");
  }
    result.delete(0,1);
    return result.toString();
}

以上是关于Find Directory Destination的主要内容,如果未能解决你的问题,请参考以下文章