标签: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:
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 }
标签:divide eve [] together ide blog font when man
原文地址:http://www.cnblogs.com/shuaih/p/7435861.html