[LeetCode]Simplify Path
转载
Question
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
本题难度Medium。
【复杂度】
时间 O(N) 空间 O(N)
【思路】
思路很简单,先将整个路径按照/
分开来,然后用一个栈,遇到..
时弹出一个,遇到.
和空字符串则不变,遇到正常路径则压入栈中。
【注意】
- 如果结果为空,要返回一个
/
- 弹出栈时要先检查栈是否为空
【代码】
public class Solution {
public String simplifyPath(String path) {
//require
StringBuilder sb=new StringBuilder();
int size=path.length();
if(size<1)
return path;
Stack<String> stack=new Stack<String>();
String[] parts=path.split("/");
//invariant
for(String part:parts){
switch(part){
case "":
case ".":
break;
case "..":
if(!stack.isEmpty())
stack.pop();
break;
default:
stack.push(part);
}
}
while(!stack.isEmpty()){
sb.insert(0,"/"+stack.pop());
}
//ensure
String ans=sb.toString();
return (ans.length()==0)?"/":ans;
}
}
参考
[Leetcode] Simplify Path 化简路径