题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
简化路径,规则:
..返回一级目录
.无效
运用stack记录路径
public class Solution {
public String simplifyPath(String path) {
String res = "";
Stack stack = new Stack<String>();
String temp="";
for(int i=1;i<=path.length();i++)
{
if(path.length()!=i &&path.charAt(i) != '/'){
temp+=path.charAt(i);
}
else
{
if (temp.equals("..") && !stack.isEmpty())
{
stack.pop();
}
if(!temp.equals(".") && !temp.equals("..") && !temp.equals(""))
{
stack.push(temp);
}
temp="";
}
}
if(stack.isEmpty())return "/";
while(!stack.isEmpty())
{
res="/"+stack.pop()+res;
}
return res;
}
}