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

Leetcode - Simplify Path

时间:2017-08-26 18:44:55      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:divide   eve   []   together   ide   blog   font   when   man   

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 }

 

 

 

 

Leetcode - Simplify Path

标签:divide   eve   []   together   ide   blog   font   when   man   

原文地址:http://www.cnblogs.com/shuaih/p/7435861.html

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