Given an absolute path for a file (Unix-style), simplify it.For example,path = "/home/", => "/home"path = "/a/./b/../../c/", => "/c"
Difficulty: 85. Although it is not difficult, there are still high requirements for the use of various tips on the stack implemented by the consumer list.
First use the string [] Split (string RegEx) function. First, separate the input string with '/' as the separator. If '.' or empty input is encountered, nothing is done. If '..' is encountered, the stack will pop up. In other cases, the corresponding elements are imported into the stack. In this way, the last simplified path is stored in the stack. We only need to extract the elements in the stack from the end to the top of the stack, and add "/" between them.
The bottom element of the stack should be used here: Stack. removelast ();
In addition, when writing, we ignore that the string is an object, '=' indicates that the memory address is the same, and equals only has the same value.
Usage of the split function: the string "Boo: And: foo", for example, split (":") returns {"boo", "and ", "foo"}; Note: trailing empty strings are not supported ded in the resulting array. for example, the result of Split ("O") is {"B", "", ": And: F "}
1 public class Solution { 2 public String simplifyPath(String path) { 3 if (path==null || path.length()==0) { 4 return ""; 5 } 6 String res = ""; 7 String[] strs = path.split("/"); 8 LinkedList<String> stack = new LinkedList<String>(); 9 for (int i=0; i<strs.length; i++) {10 if (strs[i].equals("")) continue;11 if (strs[i].equals("..") && !stack.isEmpty()) {12 stack.pop();13 }14 else if (!strs[i].equals(".") && !strs[i].equals("..")) {15 stack.push(strs[i]);16 }17 }18 if (stack.isEmpty()) return "/";19 while (!stack.isEmpty()) {20 String temp = stack.removeLast();21 res = res + "/" + temp;22 }23 return res;24 }25 }
Leetcode: simply path