Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 3, 2015 19:31
Show Gist options
  • Save cangoal/3d65403e40fc8671fc33 to your computer and use it in GitHub Desktop.
Save cangoal/3d65403e40fc8671fc33 to your computer and use it in GitHub Desktop.
LeetCode - Simplify Path
public String simplifyPath(String path) {
if(path == null || path.length() == 0) return path;
String[] arr = path.split("/");
Stack<String> stack = new Stack<String>();
for(int i = 0; i < arr.length; i++){
if(arr[i].length() > 0){
if(arr[i].equals("..")){
if(!stack.isEmpty()) stack.pop();
} else if (arr[i].equals(".")){
continue;
} else{
stack.push(arr[i]);
}
}
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
String cur = stack.pop();
sb.insert(0, cur);
sb.insert(0, "/");
}
return sb.length() > 0 ? sb.toString() : "/";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment