Leetcode - Simplify Path

Question:

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

===========================================================================================================

We need to know:

  • "." current working directory  /a /. / the command does not direct to any other directories. Basically it does nothing
  • ".." jump one level back  / c / a / .. / the current working directory is "a", if we do ".." after "a", then we jump one level back to "c"
  • "/" this is the divider of commands, which means "///" no matter how many grouped together, it is just " / ".
  • other than the previous three mentioned, they are all directory names. Those directories are the ones we need to store

Because reading the commands starts from left to right, it makes sense that we will need to loop through the command line and evaluate the meaning of each command. As we will need print out the meaningful path, we need to store each meaningful command, so we use stack. It makes becuase when we have "..", we need to know previous directory and delete it. Stack will allow us to do it this way easily.

 1 class Solution {
 2     public String simplifyPath(String path) {
 3         String[] strs = path.split("/");
 4         //create a stack to store meaningful command
 5         Stack<String> stack = new Stack<>();
 6         for (int i = 0; i < strs.length; i++) {
 7             //jump one directory back
 8             if (strs[i].equals("..")) {
 9                 if (!stack.isEmpty()) {
10                     stack.pop();
11                 }
12             } else if ((!strs[i].equals(".")) && (!strs[i].equals(""))) {
13                 stack.push(strs[i]);
14             }
15             //if the command is . or empty, then the command is not meaningful, so we will skep the execution
16         }
17         //print out the path
18         path = "";
19         while (!stack.isEmpty()) {
20             path = "/" + stack.pop() + path;
21         }
22         if (path.length() > 0) {
23             return path;
24         }
25         return "/";
26     }
27 }

 

 

 

 

转载于:https://www.cnblogs.com/shuaih/p/7435861.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值