Skip to content

Instantly share code, notes, and snippets.

@wayetan
Created March 3, 2014 02:30
Show Gist options
  • Save wayetan/9317496 to your computer and use it in GitHub Desktop.
Save wayetan/9317496 to your computer and use it in GitHub Desktop.
Simplify Path
/**
* Given an absolute path for a file (Unix-style), simplify it.
* For example,
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
* Corner Cases:
* Did you consider the case where path = "/../"?
* In this case, you should return "/".
* Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
* In this case, you should ignore redundant slashes and return "/home/foo".
*/
public class Solution {
public String simplifyPath(String path) {
if(path == null || path.length() == 0)
return "/";
Stack<String> stack = new Stack<String>();
String[] splits = path.trim().split("/");
for(String s : splits) {
if(s == null || s.length() == 0 || s.equals(".")) {
// do nothing.
continue;
} else if (s.equals("..")) {
// pop if stack is not empty;
if (stack.size() > 0)
stack.pop();
} else {
// push all others to stack
stack.push(s);
}
}
// stack can be empty.
if(stack.isEmpty())
return "/";
StringBuffer buf = new StringBuffer();
while(!stack.isEmpty()) {
buf.insert(0, stack.pop());
buf.insert(0, "/");
}
return buf.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment