码迷,mamicode.com
首页 > 其他好文 > 详细

Find Directory Destination

时间:2017-12-30 15:58:44      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:roc   []   ignore   equals   current   dea   dir   tin   nat   

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

标签:roc   []   ignore   equals   current   dea   dir   tin   nat   

原文地址:https://www.cnblogs.com/apanda009/p/8149749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!