Leetcode - Simplify Path
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于Leetcode - Simplify Path的主要内容,如果未能解决你的问题,请参考以下文章