Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
题目不难,利用正则表达式以"/"为分隔符进行分割,将"",".",".."的其他所有字符串压栈,碰到一次".."将栈中的字符串弹出(如果栈不为空的话),
最后出栈返回字符串。
public class Solution {
public String simplifyPath(String path) {
String [] list=path.split("/");
Stack<String> stack=new Stack<String>();
int len=list.length;
String res="";
for(int i=0;i<len;i++)
{
if(list[i].equals("") || list[i].equals(".")||list[i].equals(" "))continue;
if(list[i].equals(".."))
{
if(!stack.isEmpty())stack.pop();
continue;
}
stack.add(list[i]);
}
if(stack.isEmpty())return "/";
while(!stack.isEmpty())
{
res="/"+stack.pop()+res;
}
return res;
}
}