[LeetCode] Simplify Path solution report, leetcodesimplify
[Question]
Given an absolute path for a file (Unix-style), simplify it.
For example,
Path ="/home/", =>"/home"
Path ="/a/./b/../../c/", =>"/c"
Click to show corner cases.
Corner Cases:
- Did you consider the case where path =
"/../"?
In this case, you shoshould return"/".
- Another corner case is the path might contain multiple slashes
'/'Together, such"/home//foo/".
In this case, you shoshould ignore redundant slashes and return"/home/foo".
[Resolution]
Simplified file paths in Unix, including the removal of excess slashes, the removal of the current directory (./), and replacement of the parent directory.
The Tags given by the question is a stack, but I think it is more convenient to use a queue, so that the simplified directory does not need to be generated backwards.
[Java code]
public class Solution { public String simplifyPath(String path) { LinkedList<String> queue = new LinkedList<String>(); String[] names = path.split("/"); for (int i = 0; i < names.length; i++) { if ("".equals(names[i]) || ".".equals(names[i])) continue; if ("..".equals(names[i])) { if (!queue.isEmpty()) { queue.pollLast(); } } else { queue.add(names[i]); } } StringBuilder newPath = new StringBuilder(); while (!queue.isEmpty()) { newPath.append("/"); newPath.append(queue.pollFirst()); } if (newPath.length() == 0) return "/"; return newPath.toString(); }}