题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path ="/home/"
, =>"/home"
path ="/a/./b/../../c/"
, =>"/c"
分析:
路径化简。
基本思路就是使用栈来模拟进入某一路径或者返回上一级。
注意以下边界情况:
- "/../" 应化简为 "/"
- "/home//foo/" 应化简为 "/home/foo"
代码:
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Solution { public String simplifyPath(String path) { StringBuilder sb = new StringBuilder(); Stack<String> stack = new Stack<String>(); for(int i = 1, prevSlash = 0; i <= path.length(); i++){ if(i == path.length() || path.charAt(i) == '/'){ String folder = path.substring(prevSlash + 1, i); prevSlash = i; if(folder.equals("..")){ if(!stack.isEmpty()) stack.pop(); } else if(!folder.equals(".") && folder.length() > 0) stack.push(folder); } } while(!stack.isEmpty()) sb.insert(0, "/" + stack.pop()); return sb.length() == 0 ? "/" : sb.toString(); } } |