Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
The simplification of an absolute path can be done by first separating the path by "/" and interpreting each segment as subdirectory, current directory, or its parent directory. For ease of going back to the parent directory, we can use a stack to which a segment is pushed as long as it represents a subdirectory. Finally, the stack is converted into an array, and the simplified path is the concatenation of the segments in the stack preceded by a "/".
http://stupidcodergoodluck.wordpress.com/2013/11/16/leetcode-simplify-path/
Read full article from LeetCode - Simplify Path | Darren's Blog
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
The simplification of an absolute path can be done by first separating the path by "/" and interpreting each segment as subdirectory, current directory, or its parent directory. For ease of going back to the parent directory, we can use a stack to which a segment is pushed as long as it represents a subdirectory. Finally, the stack is converted into an array, and the simplified path is the concatenation of the segments in the stack preceded by a "/".
public String simplifyPath(String path) {
if (path == null)
return null;
if (path.length() == 0)
return "/";
int n = path.length();
Stack<String> stack = new Stack<String>();
String[] directories = path.split("/"); // Separate path by "/"
for (String dir : directories) {
if (dir.length() != 0) {
if (dir.equals("..")) { // Go up to its parent
if (!stack.empty())
stack.pop();
} else if (!dir.equals(".")) { // Enter its subdirectory
stack.push(dir);
}
}
// No redundant "/"
}
// Construct simplified path
if (stack.empty()) // No subdirectory
return "/";
StringBuilder result = new StringBuilder();
for (String s : stack.toArray(new String[stack.size()]))
result.append("/"+s);
return result.toString();
}
}
Also refer to http://mounttop.blogspot.com/2014/03/leetcode-simplify-path.htmlhttp://stupidcodergoodluck.wordpress.com/2013/11/16/leetcode-simplify-path/
Read full article from LeetCode - Simplify Path | Darren's Blog
No comments:
Post a Comment